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