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