Merge branch 'i507_beaker_cache'
[mediagoblin.git] / mediagoblin / app.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import os
18 import urllib
19
20 import routes
21 from webob import Request, exc
22
23 from mediagoblin import routing, util, middleware
24 from mediagoblin.mg_globals import setup_globals
25 from mediagoblin.init.celery import setup_celery_from_config
26 from mediagoblin.init import (get_jinja_loader, get_staticdirector,
27 setup_global_and_app_config, setup_workbench, setup_database,
28 setup_storage, setup_beaker_cache)
29
30
31 class MediaGoblinApp(object):
32 """
33 WSGI application of MediaGoblin
34
35 ... this is the heart of the program!
36 """
37 def __init__(self, config_path, setup_celery=True):
38 """
39 Initialize the application based on a configuration file.
40
41 Arguments:
42 - config_path: path to the configuration file we're opening.
43 - setup_celery: whether or not to setup celery during init.
44 (Note: setting 'celery_setup_elsewhere' also disables
45 setting up celery.)
46 """
47 ##############
48 # Setup config
49 ##############
50
51 # Open and setup the config
52 global_config, app_config = setup_global_and_app_config(config_path)
53
54 ##########################################
55 # Setup other connections / useful objects
56 ##########################################
57
58 # Set up the database
59 self.connection, self.db = setup_database()
60
61 # Get the template environment
62 self.template_loader = get_jinja_loader(
63 app_config.get('user_template_path'))
64
65 # Set up storage systems
66 self.public_store, self.queue_store = setup_storage()
67
68 # set up routing
69 self.routing = routing.get_mapper()
70
71 # set up staticdirector tool
72 self.staticdirector = get_staticdirector(app_config)
73
74 # set up caching
75 self.cache = setup_beaker_cache()
76
77 # Setup celery, if appropriate
78 if setup_celery and not app_config.get('celery_setup_elsewhere'):
79 if os.environ.get('CELERY_ALWAYS_EAGER'):
80 setup_celery_from_config(
81 app_config, global_config,
82 force_celery_always_eager=True)
83 else:
84 setup_celery_from_config(app_config, global_config)
85
86 #######################################################
87 # Insert appropriate things into mediagoblin.mg_globals
88 #
89 # certain properties need to be accessed globally eg from
90 # validators, etc, which might not access to the request
91 # object.
92 #######################################################
93
94 setup_globals(app = self)
95
96 # Workbench *currently* only used by celery, so this only
97 # matters in always eager mode :)
98 setup_workbench()
99
100 # instantiate application middleware
101 self.middleware = [util.import_component(m)(self)
102 for m in middleware.ENABLED_MIDDLEWARE]
103
104
105 def __call__(self, environ, start_response):
106 request = Request(environ)
107
108 # pass the request through our middleware classes
109 for m in self.middleware:
110 response = m.process_request(request)
111 if response is not None:
112 return response(environ, start_response)
113
114 ## Routing / controller loading stuff
115 path_info = request.path_info
116 route_match = self.routing.match(path_info)
117
118 ## Attach utilities to the request object
119 request.matchdict = route_match
120 request.urlgen = routes.URLGenerator(self.routing, environ)
121 # Do we really want to load this via middleware? Maybe?
122 request.session = request.environ['beaker.session']
123 # Attach self as request.app
124 # Also attach a few utilities from request.app for convenience?
125 request.app = self
126 request.locale = util.get_locale_from_request(request)
127
128 request.template_env = util.get_jinja_env(
129 self.template_loader, request.locale)
130 request.db = self.db
131 request.staticdirect = self.staticdirector
132
133 util.setup_user_in_request(request)
134
135 # No matching page?
136 if route_match is None:
137 # Try to do see if we have a match with a trailing slash
138 # added and if so, redirect
139 if not path_info.endswith('/') \
140 and request.method == 'GET' \
141 and self.routing.match(path_info + '/'):
142 new_path_info = path_info + '/'
143 if request.GET:
144 new_path_info = '%s?%s' % (
145 new_path_info, urllib.urlencode(request.GET))
146 redirect = exc.HTTPFound(location=new_path_info)
147 return request.get_response(redirect)(environ, start_response)
148
149 # Okay, no matches. 404 time!
150 request.matchdict = {} # in case our template expects it
151 return util.render_404(request)(environ, start_response)
152
153 controller = util.import_component(route_match['controller'])
154 request.start_response = start_response
155
156 # get the response from the controller
157 response = controller(request)
158
159 # pass the response through the middleware
160 for m in self.middleware[::-1]:
161 m.process_response(request, response)
162
163 return response(environ, start_response)
164
165
166 def paste_app_factory(global_config, **app_config):
167 mgoblin_app = MediaGoblinApp(app_config['config'])
168
169 return mgoblin_app