]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/lib/base.py
began work on iphone-targeted web interface
[bluechips.git] / bluechips / lib / base.py
1 """The base Controller API
2
3 Provides the BaseController class for subclassing.
4 """
5
6 from decorator import decorator
7
8 from pylons import request, session, tmpl_context as c
9 from pylons.controllers import WSGIController
10 from pylons.i18n import _, ungettext, N_
11 from pylons.templating import render_mako
12
13 from mako.exceptions import TopLevelLookupException
14
15 import bluechips.lib.helpers as h
16 from bluechips import model
17 from bluechips.model import meta
18
19
20 class BaseController(WSGIController):
21
22     def __call__(self, environ, start_response):
23         """Invoke the Controller"""
24         # WSGIController.__call__ dispatches to the Controller method
25         # the request is routed to. This routing information is
26         # available in environ['pylons.routes_dict']
27         try:
28             return WSGIController.__call__(self, environ, start_response)
29         finally:
30             meta.Session.remove()
31
32 def update_sar(record, form_result):
33     """
34     Update a SQLAlchemy record with the results of a validated form submission
35     """
36     for key, value in form_result.items():
37         setattr(record, key, value)
38
39 def redirect_on_get(action):
40     """
41     Decorator for a controller action. If the action is called with a GET
42     method, 302 redirect to the action specified.
43     """
44
45     @decorator
46     def redirect_on_get_wrap(func, *args, **kwargs):
47         if request.method == 'GET':
48             controller = request.environ['pylons.routes_dict']['controller']
49             return h.redirect_to(controller=controller, action=action)
50         else:
51             return func(*args, **kwargs)
52     return redirect_on_get_wrap
53
54 def render(name, *args, **kwargs):
55     if 'iPhone' in request.user_agent:
56         if session.get('use_non_mobile'):
57             c.mobile_client = True
58         else:
59             try:
60                 return render_mako('/mobile' + name, *args, **kwargs)
61             except TopLevelLookupException:
62                 pass
63     return render_mako(name, *args, **kwargs)
64
65 __all__ = ['c', 'h', 'render', 'model', 'meta', '_', 'ungettext', 'N_',
66            'BaseController', 'update_sar', 'redirect_on_get']