Rewrite routing.py / get_url_map
[mediagoblin.git] / mediagoblin / app.py
CommitLineData
8e1e744d 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
e5572c60
ML
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
571198c9 17import os
ec97c937 18import logging
31a8ff42 19
3d914332
E
20from mediagoblin.routing import get_url_map
21from mediagoblin.tools.routing import endpoint_to_controller
7742dcc1 22
f1d06e1d 23from werkzeug.wrappers import Request
7742dcc1 24from werkzeug.exceptions import HTTPException, NotFound
31a8ff42 25
7742dcc1 26from mediagoblin import meddleware, __version__
c0022ecc 27from mediagoblin.tools import common, translate, template
785b287f 28from mediagoblin.tools.response import render_http_exception
828fc630 29from mediagoblin.tools.theme import register_themes
152a3bfa 30from mediagoblin.tools import request as mg_request
6e7ce8d1 31from mediagoblin.mg_globals import setup_globals
073b61fe 32from mediagoblin.init.celery import setup_celery_from_config
29b6f917 33from mediagoblin.init.plugins import setup_plugins
50854db0 34from mediagoblin.init import (get_jinja_loader, get_staticdirector,
6ef75af5 35 setup_global_and_app_config, setup_locales, setup_workbench, setup_database,
0533f117 36 setup_storage, setup_beaker_cache)
05e007c1 37from mediagoblin.tools.pluginapi import PluginManager
90e342f9 38
31a8ff42 39
ec97c937
E
40_log = logging.getLogger(__name__)
41
42
8e1e744d 43class MediaGoblinApp(object):
31a8ff42 44 """
3f5cf663
CAW
45 WSGI application of MediaGoblin
46
47 ... this is the heart of the program!
31a8ff42 48 """
3f5cf663
CAW
49 def __init__(self, config_path, setup_celery=True):
50 """
51 Initialize the application based on a configuration file.
52
53 Arguments:
54 - config_path: path to the configuration file we're opening.
55 - setup_celery: whether or not to setup celery during init.
56 (Note: setting 'celery_setup_elsewhere' also disables
57 setting up celery.)
58 """
ec97c937 59 _log.info("GNU MediaGoblin %s main server starting", __version__)
3f369674 60 _log.debug("Using config file %s", config_path)
3f5cf663
CAW
61 ##############
62 # Setup config
63 ##############
64
65 # Open and setup the config
fe289be4 66 global_config, app_config = setup_global_and_app_config(config_path)
3f5cf663
CAW
67
68 ##########################################
69 # Setup other connections / useful objects
70 ##########################################
71
6ef75af5
SS
72 # load all available locales
73 setup_locales()
74
29b6f917
WKG
75 # Set up plugins -- need to do this early so that plugins can
76 # affect startup.
77 _log.info("Setting up plugins.")
78 setup_plugins()
79
3f5cf663 80 # Set up the database
3f4b5e4a 81 self.connection, self.db = setup_database()
ff94114c 82
828fc630 83 # Register themes
975be468 84 self.theme_registry, self.current_theme = register_themes(app_config)
828fc630 85
5afdd7a1 86 # Get the template environment
42ef819c 87 self.template_loader = get_jinja_loader(
3b47da8e 88 app_config.get('local_templates'),
8545dd50 89 self.current_theme,
05e007c1 90 PluginManager().get_template_paths()
8545dd50 91 )
0c8a30e6 92
5afdd7a1 93 # Set up storage systems
dccef262 94 self.public_store, self.queue_store = setup_storage()
5afdd7a1
CAW
95
96 # set up routing
48cf435d 97 self.url_map = get_url_map()
31a8ff42 98
582c4d5f 99 # set up staticdirector tool
c85c9dc7 100 self.staticdirector = get_staticdirector(app_config)
3f5cf663 101
0533f117
CAW
102 # set up caching
103 self.cache = setup_beaker_cache()
104
3f5cf663
CAW
105 # Setup celery, if appropriate
106 if setup_celery and not app_config.get('celery_setup_elsewhere'):
d9a31a39 107 if os.environ.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
3f5cf663
CAW
108 setup_celery_from_config(
109 app_config, global_config,
110 force_celery_always_eager=True)
111 else:
112 setup_celery_from_config(app_config, global_config)
113
114 #######################################################
115 # Insert appropriate things into mediagoblin.mg_globals
116 #
df9809c2
CAW
117 # certain properties need to be accessed globally eg from
118 # validators, etc, which might not access to the request
119 # object.
3f5cf663
CAW
120 #######################################################
121
243c3843 122 setup_globals(app=self)
1fd97db3
CAW
123
124 # Workbench *currently* only used by celery, so this only
125 # matters in always eager mode :)
7664b4db 126 setup_workbench()
df9809c2 127
ce5ae8da
CAW
128 # instantiate application meddleware
129 self.meddleware = [common.import_component(m)(self)
130 for m in meddleware.ENABLED_MEDDLEWARE]
0c8a30e6 131
e824570a 132 def call_backend(self, environ, start_response):
31a8ff42 133 request = Request(environ)
0c8a30e6 134
726896b6 135 # Compatibility with django, use request.args preferrably
f1d06e1d 136 request.GET = request.args
f1d06e1d 137
582c4d5f 138 ## Routing / controller loading stuff
7742dcc1 139 map_adapter = self.url_map.bind_to_environ(request.environ)
31a8ff42 140
05788ef4
E
141 # By using fcgi, mediagoblin can run under a base path
142 # like /mediagoblin/. request.path_info contains the
143 # path inside mediagoblin. If the something needs the
144 # full path of the current page, that should include
145 # the basepath.
146 # Note: urlgen and routes are fine!
f1d06e1d 147 request.full_path = environ["SCRIPT_NAME"] + request.path
05788ef4
E
148 # python-routes uses SCRIPT_NAME. So let's use that too.
149 # The other option would be:
150 # request.full_path = environ["SCRIPT_URL"]
151
871fc591 152 # Fix up environ for urlgen
d23d4b23 153 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
871fc591
E
154 if environ.get('HTTPS', '').lower() == 'off':
155 environ.pop('HTTPS')
156
3d0557bf 157 ## Attach utilities to the request object
3d0557bf
CAW
158 # Do we really want to load this via middleware? Maybe?
159 request.session = request.environ['beaker.session']
160 # Attach self as request.app
161 # Also attach a few utilities from request.app for convenience?
162 request.app = self
0c8a30e6 163
3d0557bf
CAW
164 request.db = self.db
165 request.staticdirect = self.staticdirector
166
1ec7ff2a
JW
167 request.locale = translate.get_locale_from_request(request)
168 request.template_env = template.get_jinja_env(
169 self.template_loader, request.locale)
7742dcc1
JW
170
171 def build_proxy(endpoint, **kw):
172 try:
173 qualified = kw.pop('qualified')
174 except KeyError:
175 qualified = False
176
177 return map_adapter.build(
178 endpoint,
179 values=dict(**kw),
180 force_external=qualified)
181
182 request.urlgen = build_proxy
183
1ec7ff2a
JW
184 mg_request.setup_user_in_request(request)
185
186 try:
187 endpoint, url_values = map_adapter.match()
188 request.matchdict = url_values
1ec7ff2a 189 except HTTPException as exc:
785b287f
SS
190 # Stop and render exception
191 return render_http_exception(
192 request, exc,
193 exc.get_description(environ))(environ, start_response)
1ec7ff2a 194
48cf435d 195 controller = endpoint_to_controller(endpoint)
91cf6738
NY
196
197 # pass the request through our meddleware classes
785b287f
SS
198 try:
199 for m in self.meddleware:
200 response = m.process_request(request, controller)
201 if response is not None:
202 return response(environ, start_response)
203 except HTTPException as e:
204 return render_http_exception(
205 request, e,
206 e.get_description(environ))(environ, start_response)
91cf6738 207
31a8ff42
CAW
208 request.start_response = start_response
209
785b287f
SS
210 # get the Http response from the controller
211 try:
212 response = controller(request)
213 except HTTPException as e:
214 response = render_http_exception(
215 request, e, e.get_description(environ))
0c8a30e6 216
785b287f
SS
217 # pass the response through the meddlewares
218 try:
219 for m in self.meddleware[::-1]:
220 m.process_response(request, response)
221 except HTTPException as e:
222 response = render_http_exeption(
223 request, e, e.get_description(environ))
0c8a30e6 224
e824570a
E
225 return response(environ, start_response)
226
227 def __call__(self, environ, start_response):
228 ## If more errors happen that look like unclean sessions:
229 # self.db.check_session_clean()
230
2bc8ff0d 231 try:
e824570a
E
232 return self.call_backend(environ, start_response)
233 finally:
234 # Reset the sql session, so that the next request
235 # gets a fresh session
2bc8ff0d 236 self.db.reset_after_request()
31a8ff42
CAW
237
238
5784c4e9 239def paste_app_factory(global_config, **app_config):
91903aa6
CAW
240 configs = app_config['config'].split()
241 mediagoblin_config = None
242 for config in configs:
243 if os.path.exists(config) and os.access(config, os.R_OK):
244 mediagoblin_config = config
245 break
246
247 if not mediagoblin_config:
248 raise IOError("Usable mediagoblin config not found.")
249
250 mgoblin_app = MediaGoblinApp(mediagoblin_config)
b61874b2 251
c4d71564 252 return mgoblin_app