2012-09-21 03:03:24 +08:00
|
|
|
import logging
|
2012-08-16 04:52:19 +08:00
|
|
|
import types
|
2007-12-02 10:22:19 +08:00
|
|
|
|
2012-12-17 17:49:26 +08:00
|
|
|
from django.conf import settings
|
2015-11-07 23:12:37 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed
|
2018-09-27 03:35:24 +08:00
|
|
|
from django.core.signals import request_finished
|
2013-03-06 18:12:24 +08:00
|
|
|
from django.db import connections, transaction
|
2017-01-01 02:24:00 +08:00
|
|
|
from django.urls import get_resolver, set_urlconf
|
2017-07-13 12:09:18 +08:00
|
|
|
from django.utils.log import log_response
|
2014-01-21 04:15:14 +08:00
|
|
|
from django.utils.module_loading import import_string
|
2016-06-14 15:41:58 +08:00
|
|
|
|
2018-11-20 22:45:29 +08:00
|
|
|
from .exception import convert_exception_to_response
|
2005-07-23 02:34:38 +08:00
|
|
|
|
2012-09-21 03:03:24 +08:00
|
|
|
logger = logging.getLogger('django.request')
|
2010-10-04 23:12:39 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class BaseHandler:
|
2017-09-07 20:10:49 +08:00
|
|
|
_view_middleware = None
|
|
|
|
_template_response_middleware = None
|
|
|
|
_exception_middleware = None
|
|
|
|
_middleware_chain = None
|
2005-07-23 02:34:38 +08:00
|
|
|
|
|
|
|
def load_middleware(self):
|
|
|
|
"""
|
2017-01-01 02:24:00 +08:00
|
|
|
Populate middleware lists from settings.MIDDLEWARE.
|
2005-07-23 02:34:38 +08:00
|
|
|
|
2011-07-05 00:20:16 +08:00
|
|
|
Must be called after the environment is fixed (see __call__ in subclasses).
|
2005-07-23 02:34:38 +08:00
|
|
|
"""
|
|
|
|
self._view_middleware = []
|
2010-12-07 21:57:01 +08:00
|
|
|
self._template_response_middleware = []
|
2005-10-15 10:20:35 +08:00
|
|
|
self._exception_middleware = []
|
2009-03-12 15:27:47 +08:00
|
|
|
|
2017-01-01 02:24:00 +08:00
|
|
|
handler = convert_exception_to_response(self._get_response)
|
|
|
|
for middleware_path in reversed(settings.MIDDLEWARE):
|
|
|
|
middleware = import_string(middleware_path)
|
|
|
|
try:
|
|
|
|
mw_instance = middleware(handler)
|
|
|
|
except MiddlewareNotUsed as exc:
|
|
|
|
if settings.DEBUG:
|
2016-12-29 23:27:49 +08:00
|
|
|
if str(exc):
|
2017-01-01 02:24:00 +08:00
|
|
|
logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
|
|
|
|
else:
|
|
|
|
logger.debug('MiddlewareNotUsed: %r', middleware_path)
|
|
|
|
continue
|
|
|
|
|
|
|
|
if mw_instance is None:
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
'Middleware factory %s returned None.' % middleware_path
|
|
|
|
)
|
|
|
|
|
|
|
|
if hasattr(mw_instance, 'process_view'):
|
|
|
|
self._view_middleware.insert(0, mw_instance.process_view)
|
|
|
|
if hasattr(mw_instance, 'process_template_response'):
|
|
|
|
self._template_response_middleware.append(mw_instance.process_template_response)
|
|
|
|
if hasattr(mw_instance, 'process_exception'):
|
|
|
|
self._exception_middleware.append(mw_instance.process_exception)
|
|
|
|
|
|
|
|
handler = convert_exception_to_response(mw_instance)
|
2016-05-03 00:37:49 +08:00
|
|
|
|
2009-03-12 15:27:47 +08:00
|
|
|
# We only assign to this when initialization is complete as it is used
|
|
|
|
# as a flag for initialization being complete.
|
2016-05-03 00:37:49 +08:00
|
|
|
self._middleware_chain = handler
|
2009-03-12 15:27:47 +08:00
|
|
|
|
2013-03-06 18:12:24 +08:00
|
|
|
def make_view_atomic(self, view):
|
2013-05-19 23:55:12 +08:00
|
|
|
non_atomic_requests = getattr(view, '_non_atomic_requests', set())
|
|
|
|
for db in connections.all():
|
2016-04-04 08:37:32 +08:00
|
|
|
if db.settings_dict['ATOMIC_REQUESTS'] and db.alias not in non_atomic_requests:
|
2013-05-19 23:55:12 +08:00
|
|
|
view = transaction.atomic(using=db.alias)(view)
|
2013-03-06 18:12:24 +08:00
|
|
|
return view
|
|
|
|
|
2006-09-28 09:56:02 +08:00
|
|
|
def get_response(self, request):
|
2016-05-03 00:37:49 +08:00
|
|
|
"""Return an HttpResponse object for the given HttpRequest."""
|
|
|
|
# Setup default url resolver for this thread
|
|
|
|
set_urlconf(settings.ROOT_URLCONF)
|
|
|
|
response = self._middleware_chain(request)
|
2014-05-26 04:52:47 +08:00
|
|
|
response._closable_objects.append(request)
|
2017-07-13 12:09:18 +08:00
|
|
|
if response.status_code >= 400:
|
|
|
|
log_response(
|
|
|
|
'%s: %s', response.reason_phrase, request.path,
|
|
|
|
response=response,
|
|
|
|
request=request,
|
2016-04-14 23:12:35 +08:00
|
|
|
)
|
2010-10-30 15:19:04 +08:00
|
|
|
return response
|
|
|
|
|
2016-05-03 00:37:49 +08:00
|
|
|
def _get_response(self, request):
|
2016-06-14 15:41:58 +08:00
|
|
|
"""
|
|
|
|
Resolve and call the view, then apply view, exception, and
|
|
|
|
template_response middleware. This method is everything that happens
|
|
|
|
inside the request/response middleware.
|
|
|
|
"""
|
2016-05-03 00:37:49 +08:00
|
|
|
response = None
|
|
|
|
|
|
|
|
if hasattr(request, 'urlconf'):
|
|
|
|
urlconf = request.urlconf
|
|
|
|
set_urlconf(urlconf)
|
|
|
|
resolver = get_resolver(urlconf)
|
|
|
|
else:
|
|
|
|
resolver = get_resolver()
|
|
|
|
|
|
|
|
resolver_match = resolver.resolve(request.path_info)
|
|
|
|
callback, callback_args, callback_kwargs = resolver_match
|
|
|
|
request.resolver_match = resolver_match
|
|
|
|
|
|
|
|
# Apply view middleware
|
|
|
|
for middleware_method in self._view_middleware:
|
|
|
|
response = middleware_method(request, callback, callback_args, callback_kwargs)
|
|
|
|
if response:
|
2016-07-19 16:45:32 +08:00
|
|
|
break
|
2016-05-03 00:37:49 +08:00
|
|
|
|
2016-07-19 16:45:32 +08:00
|
|
|
if response is None:
|
|
|
|
wrapped_callback = self.make_view_atomic(callback)
|
|
|
|
try:
|
|
|
|
response = wrapped_callback(request, *callback_args, **callback_kwargs)
|
|
|
|
except Exception as e:
|
|
|
|
response = self.process_exception_by_middleware(e, request)
|
2016-05-03 00:37:49 +08:00
|
|
|
|
|
|
|
# Complain if the view returned None (a common error).
|
|
|
|
if response is None:
|
|
|
|
if isinstance(callback, types.FunctionType): # FBV
|
|
|
|
view_name = callback.__name__
|
|
|
|
else: # CBV
|
|
|
|
view_name = callback.__class__.__name__ + '.__call__'
|
|
|
|
|
|
|
|
raise ValueError(
|
|
|
|
"The view %s.%s didn't return an HttpResponse object. It "
|
|
|
|
"returned None instead." % (callback.__module__, view_name)
|
|
|
|
)
|
|
|
|
|
|
|
|
# If the response supports deferred rendering, apply template
|
|
|
|
# response middleware and then render the response
|
|
|
|
elif hasattr(response, 'render') and callable(response.render):
|
|
|
|
for middleware_method in self._template_response_middleware:
|
|
|
|
response = middleware_method(request, response)
|
|
|
|
# Complain if the template response middleware returned None (a common error).
|
|
|
|
if response is None:
|
|
|
|
raise ValueError(
|
|
|
|
"%s.process_template_response didn't return an "
|
|
|
|
"HttpResponse object. It returned None instead."
|
|
|
|
% (middleware_method.__self__.__class__.__name__)
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
|
|
|
response = response.render()
|
|
|
|
except Exception as e:
|
|
|
|
response = self.process_exception_by_middleware(e, request)
|
|
|
|
|
|
|
|
return response
|
|
|
|
|
2015-06-05 21:30:03 +08:00
|
|
|
def process_exception_by_middleware(self, exception, request):
|
|
|
|
"""
|
|
|
|
Pass the exception to the exception middleware. If no middleware
|
|
|
|
return a response for this exception, raise it.
|
|
|
|
"""
|
|
|
|
for middleware_method in self._exception_middleware:
|
|
|
|
response = middleware_method(request, exception)
|
|
|
|
if response:
|
|
|
|
return response
|
|
|
|
raise
|
2018-09-27 03:35:24 +08:00
|
|
|
|
|
|
|
|
|
|
|
def reset_urlconf(sender, **kwargs):
|
|
|
|
"""Reset the URLconf after each request is finished."""
|
|
|
|
set_urlconf(None)
|
|
|
|
|
|
|
|
|
|
|
|
request_finished.connect(reset_urlconf)
|