django有两种运行方式
1,通过python manage.py runserver运行自带的web server
2,通过mod_python
两种方式但最后的request生成方法都是继承自django.http.HttpReques
第一种方式, runserver参数最后实际执行的是django.core.management.commands.runserver模块
runserver.py中关键代码为
run(addr, int(port), handler)
run函数详细定义(django.core.servers.basehttp.py):
def run(addr, port, wsgi_handler):
server_address = (addr, port)
httpd = WSGIServer(server_address, WSGIRequestHandler)
httpd.set_app(wsgi_handler)
httpd.serve_forever()
不难发现,生成一httpServer对象,并将wsgi_handler作为http请求handle
第二种方式,以Apache为例那更简明了
<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonDebug On
</Location>
PythonHandler指明django.core.handlers.modpython为处理每个http请求的handle
django.core.handlers.modpython定义了ModPythonHandler和ModPythonRequest
ModPythonHandler和WSGIHandler内容基本相同
首先生成request对象,然后处理各中间件和返回response,关键代码如下:
try:
try:
request = self.request_class(environ)
except UnicodeDecodeError:
response = http.HttpResponseBadRequest()
else:
response = self.get_response(request)
# Apply response middleware
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
response = self.apply_response_fixes(request, response)
finally:
signals.request_finished.send(sender=self.__class__)
get_response定义在django.core.handlers.base.py BaseHandler类中:
def get_response(self, request)
该函数关键代码如下:
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
try:
callback, callback_args, callback_kwargs = resolver.resolve(
request.path_info) #此处为寻找view函数,即urls.py中定义的每个url具体的处理函数
# Apply view middleware #处理中间件
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
return response
try:
response = callback(request, *callback_args, **callback_kwargs) #执行view函数
except Exception, e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
return response
raise
if response is None:
try:
view_name = callback.func_name # If it's a function
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class
raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)
return response #返回response
有一张图很明了,对理解django处理流程很有帮助
先写到这,分析源代码对自己理解django确实帮助大,发现django源码很易懂,我想这也跟python语言本身有很大的关系
Django源码分析--引导
最新推荐文章于 2020-09-26 05:55:59 发布