Wed Development - Dynamically Generated News Index
Jean-Paul Calderone
exarkun at divmod.com
Sun Dec 18 02:52:28 EST 2005
On 17 Dec 2005 23:14:33 -0800, infidel02 at lycos.com wrote:
>Hi to all,
>
>I am somewhat somewhat new to Python, but apart from this I am just not
>seeing lots of resources on what I am trying to do. I have seen them
>in other languages like PHP and ASP.
>
>I am building a simple MySQL news database, which would contain, a
>headline, a date, main story(body) and a graphic associated with each
>story. I would like to generate an index of the pages in this database
>( ie a news index with links to the articles) an to have a news
>administrator upload and delete stories graphic etc.
>
>I have read many articles on Python CGI programming and I have Googled
>extensively, but have not seen any kind of examples of how this can be
>done in Python.
>
>I would be grateful for any assistance or pointers.
Using Nevow and Twisted Web, this might look something like (untested)...
from nevow import rend, loaders, tags
class NewsIndex(rend.Page):
docFactory = loaders.stan(tags.html[
tags.body(render=tags.directive('index'))])
def __init__(self, connpool):
super(NewsIndex, self).__init__()
self.connpool = connpool
def _retrieveIndex(self):
return self.connpool.runQuery(
"SELECT articleId, articleTitle, articleImage FROM articles")
def _retrieveArticle(self, articleId):
return self.connpool.runQuery(
"SELECT articleBody FROM articles WHERE articleId = ?",
(articleId,))
def render_index(self, ctx, data):
return self._retrieveIndex().addCallback(lambda index: [
tags.div[
tags.a(href=articleID)[
tags.img(src=articleImage),
articleTitle]]
for (articleID, articleTitle, articleImage)
in index])
def childFactory(self, ctx, name):
return self._retrieveArticle(name).addCallback(lambda articleBody:
ArticlePage(articleBody))
class ArticlePage(rend.Page):
docFactory = loaders.stan(tags.html[
tags.body(render=tags.directive('article'))])
def __init__(self, articleBody):
super(ArticlePage, self).__init__()
self.articleBody = articleBody
def render_article(self, ctx, data):
return self.articleBody
from twisted.enterprise import adbapi
# Whatever DB-API 2.0 stuff you want
cp = adbapi.ConnectionPool('pypgsql', ...)
from twisted.application import service, internet
from nevow import appserver
application = service.Application("News Site")
webserver = appserver.NevowSite(NewsIndex(cp))
internet.TCPServer(80, webserver).setServiceParent(application)
# Run with twistd -noy <whatever you name this file>
For more information about Nevow, checkout the Wiki - <http://divmod.org/trac/wiki/DivmodNevow> - or the mailing list - <http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web> - or the IRC channel - #twisted.web on freenode.
Jean-Paul
More information about the Python-list
mailing list