django之def get_response(self, request):
class BaseHandler(object)方法get_response,控制着处理请求的流程,调用中间件,返回请求。
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest" # Setup default url resolver for this thread, this code is outside
# the try/except so we don't get a spurious "unbound local
# variable" exception in the event an exception is raised before
# resolver is set
urlconf = settings.ROOT_URLCONF#获取根urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.get_resolver(urlconf)#生成url解决子
# Use a flag to check if the response was rendered to prevent
# multiple renderings or to force rendering if necessary.
response_is_rendered = False
try:
response = None
# Apply request middleware
for middleware_method in self._request_middleware:调用中间件
response = middleware_method(request)
if response:
break if response is None:
if hasattr(request, 'urlconf'):
# Reset url resolver with a custom URLconf.
urlconf = request.urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.get_resolver(urlconf) resolver_match = resolver.resolve(request.path_info)#由路径找到url匹配的view函数
callback, callback_args, callback_kwargs = resolver_match
request.resolver_match = resolver_match#给请求添加匹配子属性 # Apply view middleware
for middleware_method in self._view_middleware:#调用view中间件
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break if response is None:
wrapped_callback = self.make_view_atomic(callback)#真正调用view函数
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs)
except Exception as e:
response = self.process_exception_by_middleware(e, request) # 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
if 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) response_is_rendered = True except http.Http404 as exc:
logger.warning('Not Found: %s', request.path,
extra={
'status_code': 404,
'request': request
})
if settings.DEBUG:
response = debug.technical_404_response(request, exc)
else:
response = self.get_exception_response(request, resolver, 404, exc) except PermissionDenied as exc:
logger.warning(
'Forbidden (Permission denied): %s', request.path,
extra={
'status_code': 403,
'request': request
})
response = self.get_exception_response(request, resolver, 403, exc) except MultiPartParserError as exc:
logger.warning(
'Bad request (Unable to parse request body): %s', request.path,
extra={
'status_code': 400,
'request': request
})
response = self.get_exception_response(request, resolver, 400, exc) except SuspiciousOperation as exc:
# The request logger receives events for any problematic request
# The security logger receives events for all SuspiciousOperations
security_logger = logging.getLogger('django.security.%s' %
exc.__class__.__name__)
security_logger.error(
force_text(exc),
extra={
'status_code': 400,
'request': request
})
if settings.DEBUG:
return debug.technical_500_response(request, *sys.exc_info(), status_code=400) response = self.get_exception_response(request, resolver, 400, exc) except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise except: # Handle everything else.
# Get the exception info now, in case another exception is thrown later.
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:#调用响应中间件
response = middleware_method(request, response)
# Complain if the response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
response = self.apply_response_fixes(request, response)
except: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) response._closable_objects.append(request) # If the exception handler returns a TemplateResponse that has not
# been rendered, force it to be rendered.
if not response_is_rendered and callable(getattr(response, 'render', None)):
response = response.render() return response
process_request、process_view按中间件的从上到下的顺序执行,process_template_response process_response、process_exception按从下到上的顺序执行。最终response都要经过process_response中间件。所以django-debug-toolbar是通过中间件在响应阶段记录数据。
django之def get_response(self, request):的更多相关文章
- django的views里面的request对象详解大全
简介 HTTP 应用的信息是通过 请求报文 和 响应报文 传递的,关于更多的相关知识,可以阅读<HTTP权威指南>获得. 其中 请求报文 由客户端发送,其中包含和许多的信息,而 djang ...
- Django REST framework 第二章 Request and Response
此章节开始真正的撰写REST framework的核心代码,介绍一系列必要的建立设计 Request Objects REST framework介绍了一个Request对象用来扩展常规的HttpRe ...
- django -- url (模版语言{{ request.path_info }})
在django的模版语言中中可以使用 {{ request.path_info }} 帮助生成url. urls.py from django.conf.urls import url, incl ...
- Django的views中的request
Django使用request和response对象在系统间传递状态. 当一个页面被请示时,Django创建一个包含请求元数据的 HttpRequest 对象. 然后Django调入合适的视图,把Ht ...
- DRF (Django REST framework) 中的Request 与 Response
DRF中的Request 与 Response 1. Request - REST framework 传入视图的request对象不再是Django默认的HttpRequest对象,而是REST f ...
- Django 源码小剖: URL 调度器(URL dispatcher)
在刚开始接触 django 的时候, 我们尝试着从各种入门文档中创建一个自己的 django 项目, 需要在 mysite.urls.py 中配置 URL. 这是 django url 匹配处理机制的 ...
- Django 源码小剖: 初探中间件(middleware)
因为考虑到文章的长度, 所以 BaseHandler 的展开被推迟了. 在 BaseHandler 中隐藏着中间件的信息, 较常见的 SessionMiddleware 就已经默认安装. BaseH ...
- Django HTTP处理流程(自我总结)
Django中由wsgi模块接管http请求,核心处理方法为get_wsgi_application,其定义如下: def get_wsgi_application(): ""&q ...
- Django学习之七:Django 中间件
目录 Django 中间件 自定义中间件 - - - 大体两种方式 将中间件移除 实例 中间件加载源码阅读 总结 Django 中间件 Tips: 更新日志: 2019.01.31 更新django中 ...
随机推荐
- ul或者ol中添加li元素
<!doctype html><html> <head> <meta charset="utf-8"> ...
- Java事件监听器的四种实现方式
自身类作为事件监听器 外部类作为事件监听器 匿名内部类作为事件监听器 内部类作为事件监听器 自身类作为事件监听器: import javax.swing.*; import java.awt.*; i ...
- 阿里云ECS服务器环境搭建——ubuntu16.04图形界面的安装
阿里云ECS服务器环境搭建——ubuntu16.04图形界面的安装 最近琢磨着想在服务器上搭建一个hexo博客,于是就在阿里云上买了一个云服务器ECS,远程接入后默认给的是一个命令窗口,没有图形界面, ...
- C++11--时钟和计时器<chrono>
/* 介绍<chrono> -- 一个精确中立的时间和日期库 * 时钟: * * std::chrono::system_clock: 依据系统的当前时间 (不稳定) * std::chr ...
- http系列(一)
一.关于Url URI由URL和URN组成,URI即统一资源标识符,URL即统一资源定位符,URN即统一资源名称. 现在最常用的是URL. 二.http请求/响应报文 请求报文:请求行.请求头部.空行 ...
- hadoop MapReduce —— 输出每个单词所对应的文件
下面是四个文件及其内容. 代码实现: Mapper: package cn.tedu.invert; import java.io.IOException; import org.apache.had ...
- maven(一 基本操作 命令 标签)
原来一直没有使用maven 小公司,只是听说过这个东西,我没事就喜欢 去学习一些新东西.maven学了几次,但是 没有用上 所以 最后还是忘记了,或者说不知道怎么使用maven,一年半以前公司 改革 ...
- fiddler 手机 https 抓包 以及一些fiddler无法解决的https问题http2、tcp、udp、websocket证书写死在app中无法抓包
原文: https://blog.csdn.net/wangjun5159/article/details/52202059 fiddler手机抓包原理 fiddler手机抓包的原理与抓pc上的web ...
- keepalived主备节点都配置vip,vip切换异常案例分析
原文地址:http://blog.51cto.com/13599730/2161622 参考地址:https://blog.csdn.net/qq_14940627/article/details/7 ...
- axublogcms1.0.6|代码审计
这周的审计任务,两天前的任务呀~拖延症呀~ 这次审计一个博客----auxblogcms1.0.6,网上也有所记载,我下面会做个总结. axublog是一款php个人博客系统,小巧强大的PHP+MyS ...