django的request对象是在什么时候创建的?通过django源代码解释
时间: 2023-05-23 21:01:35 浏览: 104
在Django中,request对象是在Django的HTTP请求处理流程中创建的。具体来说,request对象是在WSGIHandler的get_response方法中创建的,而get_response方法是在Django应用程序接收到HTTP请求后被调用的。在get_response方法中,WSGIHandler首先调用中间件处理器(Middleware)来对request对象进行处理,然后根据URLConf将请求路由到相应的视图函数中。在路由到视图函数之前,WSGIHandler还会对request对象进行一些其他处理,比如将协议头(如HTTP头)中的信息添加到request对象中。
下面是WSGIHandler的get_response方法的代码片段,可以看到在该方法最开始的位置就创建了request对象:
def get_response(self, request):
# Setup default url resolver
set_urlconf(settings.ROOT_URLCONF)
# Reset url resolver cache if requested
if getattr(request, '_wsgi_request', None):
clear_url_caches()
# Apply request middleware
response = self.apply_request_middleware(request)
if response:
# If a middleware returns a response, run it right here!
response._handler_class = None
return response
# Resolve the request
resolver = get_resolver(get_urlconf(), subdomain=request.get_host().split(':')[0])
callback, callback_args, callback_kwargs = resolver.resolve(request.path_info)
request.resolver_match = ResolverMatch(callback, callback_args, callback_kwargs, None)
# Apply view middleware
response = self.apply_view_middleware(request, callback, callback_args, callback_kwargs)
if response:
# If a middleware returns a response, run it right here!
response._handler_class = None
return response
try:
response = callback(request, *callback_args, **callback_kwargs)
阅读全文