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