| 1 | import sys |
| 2 | import urllib |
| 3 | |
| 4 | from beaker.middleware import SessionMiddleware |
| 5 | import routes |
| 6 | import pymongo |
| 7 | from webob import Request, exc |
| 8 | |
| 9 | from mediagoblin import routing, util |
| 10 | |
| 11 | |
| 12 | class Error(Exception): pass |
| 13 | class ImproperlyConfigured(Error): pass |
| 14 | |
| 15 | |
| 16 | def load_controller(string): |
| 17 | module_name, func_name = string.split(':', 1) |
| 18 | __import__(module_name) |
| 19 | module = sys.modules[module_name] |
| 20 | func = getattr(module, func_name) |
| 21 | return func |
| 22 | |
| 23 | |
| 24 | class MediagoblinApp(object): |
| 25 | """ |
| 26 | Really basic wsgi app using routes and WebOb. |
| 27 | """ |
| 28 | def __init__(self, database, user_template_path=None): |
| 29 | self.template_env = util.get_jinja_env(user_template_path) |
| 30 | self.db = database |
| 31 | self.routing = routing.get_mapper() |
| 32 | |
| 33 | def __call__(self, environ, start_response): |
| 34 | request = Request(environ) |
| 35 | path_info = request.path_info |
| 36 | route_match = self.routing.match(path_info) |
| 37 | |
| 38 | # No matching page? |
| 39 | if route_match is None: |
| 40 | # Try to do see if we have a match with a trailing slash |
| 41 | # added and if so, redirect |
| 42 | if not path_info.endswith('/') \ |
| 43 | and request.method == 'GET' \ |
| 44 | and self.routing.match(path_info + '/'): |
| 45 | new_path_info = path_info + '/' |
| 46 | if request.GET: |
| 47 | new_path_info = '%s?%s' % ( |
| 48 | new_path_info, urllib.urlencode(request.GET)) |
| 49 | redirect = exc.HTTPTemporaryRedirect(location=new_path_info) |
| 50 | return request.get_response(redirect)(environ, start_response) |
| 51 | |
| 52 | # Okay, no matches. 404 time! |
| 53 | return exc.HTTPNotFound()(environ, start_response) |
| 54 | |
| 55 | controller = load_controller(route_match['controller']) |
| 56 | request.start_response = start_response |
| 57 | |
| 58 | request.matchdict = route_match |
| 59 | request.app = self |
| 60 | request.template_env = self.template_env |
| 61 | request.urlgen = routes.URLGenerator(self.routing, environ) |
| 62 | request.session = request.environ['beaker.session'] |
| 63 | |
| 64 | return controller(request)(environ, start_response) |
| 65 | |
| 66 | |
| 67 | def paste_app_factory(global_config, **kw): |
| 68 | connection = pymongo.Connection() |
| 69 | db = connection[kw.get('db_name', 'mediagoblin')] |
| 70 | |
| 71 | mgoblin_app = MediagoblinApp( |
| 72 | db, user_template_path=kw.get('local_templates')) |
| 73 | beakered_app = SessionMiddleware( |
| 74 | mgoblin_app, |
| 75 | {'session.type': 'file', |
| 76 | 'session.cookie_expires': True}) |
| 77 | |
| 78 | return beakered_app |