书接上回, 我们说完了django重启的过程, 留下了一个inner_run, 这一节, 我们就来看看inner_run里是如何执行的
inner_run
代码太长, 前面的信息显示就跳过了.
handler = self.get_handler(*args, **options)
run(self.addr, int(self.port), handler, ipv6=self.use_ipv6,
threading=threading, server_cls=self.server_cls)
首先是get_handler, 这个handler是用来处理request请求的.
首先, 父类的get_handler拿到的wsgi handler, 但是在开发环境, 默认返回的是附带有静态资源管理的handler, 也就是StaticFilesHandler.
拿到handler以后, 调用django自带的run函数
httpd_cls默认是django的htppbase中的WSGIServer, WSGIServer又是继承自python系统库simple_server.WSGIServer
这里的先捋捋server的继承关系
BaseServer => TCPServer => WSGIServer(simple_server) => WSGIServer(basehttp)
simple_server.WSGIServer没有额外的初始化动作, 跳到再上一层TCPServer先是把ip, 端口号以及request请求注册到了BaseServer中, 因为有继承关系, 这些注册的信息, 自然也绑定到了当前对象上. 后续就是TCP服务创建过程.
tcp服务创建完, 我们的WSGIServer其实也就创建好了, 此时回到
httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
if threading:
# ThreadingMixIn.daemon_threads indicates how threads will behave on an
# abrupt shutdown; like quitting the server by the user or restarting
# by the auto-reloader. True means the server will not wait for thread
# termination before it quits. This will make auto-reloader faster
# and will prevent the need to kill the server manually if a thread
# isn't terminating correctly.
httpd.daemon_threads = True
httpd.set_app(wsgi_handler)
httpd.serve_forever()
httpd是WSGIServer的一个实例对象, set_app()中, 开发环境下, 将StaticFilesHandler作为应用实体绑定在了httpd上, 最后, serve_forever(), 这里的调用的是基类BaseServer的serve_forever.
_ServerSelector: SelectSelector的实例对象, 主要任务还是实现TCP通信的select操作.
详细内容, 参考python中的selectors模块
最后, 代码执行到
ready = selector.select(poll_interval)
进程挂起, 等待请求来临. 至此. runserver服务的启动也就完了. 接下来就是每次request到来后, django对其如何处理, 敬请期待下一节.
来源:CSDN
作者:cierlongbu
链接:https://blog.csdn.net/cierlongbu/article/details/104004987