]> asedeno.scripts.mit.edu Git - bluechips.git/blob - bluechips/lib/base.py
e485c5732139b9768f4ba9be38821565615763f3
[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 any([x in request.user_agent for x in ('iPhone','webOS')]):
56         if 'use_non_mobile' in request.params:
57             session['use_non_mobile'] = (request.params['use_non_mobile'] ==
58                                          'yes')
59         if session.get('use_non_mobile'):
60             c.mobile_client = True
61         else:
62             try:
63                 return render_mako('/mobile' + name, *args, **kwargs)
64             except TopLevelLookupException:
65                 # If a mobile template doesn't exist for this page, don't show
66                 # the 'use mobile interface' link.
67                 c.mobile_client = False
68     return render_mako(name, *args, **kwargs)
69
70 def get_users():
71     return meta.Session.query(model.User.id, model.User).\
72         order_by(model.User.resident.desc(), model.User.username)
73
74 __all__ = ['c', 'h', 'render', 'model', 'meta', '_', 'ungettext', 'N_',
75            'BaseController', 'update_sar', 'redirect_on_get', 'get_users']