Skip to content

Instantly share code, notes, and snippets.

@riffm
Created December 18, 2010 10:57
Show Gist options
  • Save riffm/746404 to your computer and use it in GitHub Desktop.
Save riffm/746404 to your computer and use it in GitHub Desktop.
'''
- WebHandler wraps next WebHandler and make desicion what to return (like decorators)
- WebHandler may return Response object and that will be the end of current chain, even
there are other handlers.
- If WebHandler returns None means that this chain is not for current request,
so we ask next chain. If this chain was last status 404 returns to client.
- There are two datastructures for data accumulation 'data' and 'env'.
'data' - template data
'env' - environment data (db sessions, template renderers, url_for, ...)
These structures are mutable during request processing. The only significant thing,
data appended in this structures by WebHandler are visible only for wrapped handlers
(next in chain till the end of chain).
- 'url_for' may return relative urls for example 'news.index' and '.index' (in news_list)
are the same.
'''
from insanities import web, template
from mage import sqla
import cfg
t = template.Template({'mint':template.mint(cfg.TEMPLATES)},
cache=True)
def config(env, data, next_handler):
env.cfg = cfg
env.db = sqla.construct_maker(cfg.DATABASES)()
env.template = t
env.url_for = web.Reverse.from_handler(next_handler)
try:
return next_handler(env, data)
finally:
env.db.close()
def index_data(env, data, next_handler):
data.title = 'index'
if env.request.method == 'GET':
data.news_url = env.url_for('news.index')
return next_handler(env, data)
def news_list(env, data, next_handler):
data.items = env.db.query(News).limit(10)
return next_handler(env, data)
def render_to(name):
def wrapper(env, data, next_handler):
return env.render_to_response(name, data)
return wrapper
app = web.handler(config) | web.List(
web.match('/', 'index') | index_data | render_to('index.html'),
web.prefix('/news') | web.namespace('news') | web.List(
web.match('/', 'index') | news_list | render_to('news_list.html'),
web.match('/<int:id>', 'item') | news_item | render_to('news_item.html'),
),
web.prefix('/articles') | web.namespace('articles') | web.List(
web.match('/', 'index') | articles | render_to('articles.html'),
web.match('/<int:id>', 'item') | article | render_to('article.html'),
),
)
if __name__ == '__main__':
mage.serve(app.as_wsgi(), 8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment