django之runserver命令分析
def inner_run(self, *args, **options):#runserver命令执行的内容
# If an exception was silenced in ManagementUtility.execute in order
# to be raised in the child process, raise it now.
autoreload.raise_last_exception() threading = options.get('use_threading')
shutdown_message = options.get('shutdown_message', '')
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' self.stdout.write("Performing system checks...\n\n")
self.check(display_num_errors=True)
self.check_migrations()
now = datetime.now().strftime('%B %d, %Y - %X')
if six.PY2:
now = now.decode(get_system_encoding())
self.stdout.write(now)
self.stdout.write((
"Django version %(version)s, using settings %(settings)r\n"
"Starting development server at http://%(addr)s:%(port)s/\n"
"Quit the server with %(quit_command)s.\n"
) % {
"version": self.get_version(),
"settings": settings.SETTINGS_MODULE,
"addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr,
"port": self.port,
"quit_command": quit_command,
}) try:
handler = self.get_handler(*args, **options)#调用get_internal_wsgi_application()
run(self.addr, int(self.port), handler,
ipv6=self.use_ipv6, threading=threading)
except socket.error as e:
# Use helpful error messages instead of ugly tracebacks.
ERRORS = {
errno.EACCES: "You don't have permission to access that port.",
errno.EADDRINUSE: "That port is already in use.",
errno.EADDRNOTAVAIL: "That IP address can't be assigned to.",
}
try:
error_text = ERRORS[e.errno]
except KeyError:
error_text = force_text(e)
self.stderr.write("Error: %s" % error_text)
# Need to use an OS exit because sys.exit doesn't work in a thread
os._exit(1)
except KeyboardInterrupt:
if shutdown_message:
self.stdout.write(shutdown_message)
sys.exit(0)
def get_handler(self, *args, **options):
return get_internal_wsgi_application()
def get_internal_wsgi_application():
from django.conf import settings
app_path = getattr(settings, 'WSGI_APPLICATION')
if app_path is None:
return get_wsgi_application()
try:
return import_string(app_path)
except ImportError as e:
msg = (
"WSGI application '%(app_path)s' could not be loaded; "
"Error importing module: '%(exception)s'" % ({
'app_path': app_path,
'exception': e,
})
)
six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg),
sys.exc_info()[2])
项目的wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mytest.settings")
application = get_wsgi_application()
而from django.core.wsgi import get_wsgi_application为:
def get_wsgi_application():
"""
The public interface to Django's WSGI support. Should return a WSGI
callable.
Allows us to avoid making django.core.handlers.WSGIHandler public API, in
case the internal WSGI implementation changes or moves in the future.
"""
django.setup()
return WSGIHandler()
该函数会返回一个WSGIHandler()对象。
在项目的setting文件中:
WSGI_APPLICATION = 'mytest.wsgi.application'指示如何获得app,所以构造server的handler是一个可调用的对象,调用时执行的函数:
class WSGIHandler(base.BaseHandler):
initLock = Lock()
request_class = WSGIRequest def __call__(self, environ, start_response):
# Set up middleware if needed. We couldn't do this earlier, because
# settings weren't available.
if self._request_middleware is None:#判断中间件是否为空,第一次调用的话为空,后面调用就不用再load了
with self.initLock:
try:
# Check that middleware is still uninitialized.
if self._request_middleware is None:
self.load_middleware()
except:
# Unload whatever middleware we got
self._request_middleware = None
raise set_script_prefix(get_script_name(environ))
signals.request_started.send(sender=self.__class__, environ=environ)#请求开始信号动作
try:
request = self.request_class(environ)#产生一个request对象
except UnicodeDecodeError:
logger.warning('Bad Request (UnicodeDecodeError)',
exc_info=sys.exc_info(),
extra={
'status_code': 400,
}
)
response = http.HttpResponseBadRequest()
else:
response = self.get_response(request)#调用handler的生成响应的方法,该方法会调用中间件。 response._handler_class = self.__class__ status = '%s %s' % (response.status_code, response.reason_phrase)
response_headers = [(str(k), str(v)) for k, v in response.items()]
for c in response.cookies.values():
response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
start_response(force_str(status), response_headers)
if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
response = environ['wsgi.file_wrapper'](response.file_to_stream)
return response
django server中的basehttp的run函数用来产生server的:
def run(addr, port, wsgi_handler, ipv6=False, threading=False):
server_address = (addr, port)
if threading:#如果线程处理请求的话,server类就继承自socketserver.ThreadingMixIn, WSGIServer,使server的process
_request的方法为ThreadingMixIn的
httpd_cls = type(str('WSGIServer'), (socketserver.ThreadingMixIn, WSGIServer), {})
else:
httpd_cls = 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()#调用process_request
django之runserver命令分析的更多相关文章
- Django - Python3 常用命令
1.创建Django 项目 执行命令 django-admin.py startproject project_name 2.创建app 执行命令 注意:要先进入项目目录下,cd project_na ...
- web 架构 /http协议,状态码,django中常用命令
什么是web应用? web应用 架构 :B/S架构 | C/S架构 网站:BS架构其实就是应用程序: B是浏览器 S是sever(实现了wsgi协议,实现了socket的服务端) + applicat ...
- Django 自定义扩展命令
import datetime import logger from django.conf import settings from django.db.models import Q from d ...
- Django manage.py 命令详解
manage.py 查看命令的作用的语句 C:\Users\Administrator> python manage.py help Type 'manage.py help <subco ...
- MySQL中使用SHOW PROFILE命令分析性能的用法整理(配合explain效果更好,可以作为优化周期性检查)
这篇文章主要介绍了MySQL中使用show profile命令分析性能的用法整理,show profiles是数据库性能优化的常用命令,需要的朋友可以参考下 show profile是由Jerem ...
- nohup 、&、 2>&1 命令分析
nohup的意思是不间断的运行,&的意思是后台运行,2>&1的意思是标准输出和错误输出都重定向到同一个文件. 简单地说nohup运行时即使关掉控制台,它该运行还是运行. http ...
- 利用shell命令分析服务器日志
在没有专业日志分析系统的情况下,我们有时需要对日志进行简单的分析,下面列出一些常用的shell命令分析日志的方法,一定要收藏 1.查看有多少个ip访问 awk '{print $1}' log_f ...
- linux日常常用命令分析
日志处理: 测试网络路由: xargs使用方法: tcpdump命令分析: dd 写入磁盘测试 cpu个数: 查看网卡流量 查看端口联通情况,临时加端口 ntpdate同步: 可以取出变动的密码: 导 ...
- ffmpeg 转码并截图的命令分析
一.转码并截图的命令分析: 1.转码并截图,将码率转换为900Kffmpeg -i E:\\1.MOV -i E:\\123.jpg -filter_complex overlay=W-w -b:v ...
随机推荐
- c#读取Sybase中文乱码的解决办法
最近需要从Sybase数据库中获取数据.用Sybase.Data.AseClient连接的话比较简单,但中文数据会有乱码.用Sybase自带的工具SQL Advantage设置好编码和语言,是可以正常 ...
- JS属性描述符之Object.defineProperty()定义对象属性特性
一.Object.defineProperty的作用 用来给对象新增属性,和修改对象中的属性. 二.JS对象中的描述符 js对象中两种属性描述符:数据描述符和存取描述符(访问描述符). 注意事项: 1 ...
- JS之事件机制
一.绑定事件的3种方式 1.内联绑定事件 2.on+事件名,绑定事件程序 3.通过addEventListener/removeEventListener绑定事件 不支持ie9之前的浏览器,ie9之前 ...
- bzoj5052: 繁忙的财政官
求区间内相差最小的两个数的差 分sqrt(n)块,预处理两个数在块内,以及一个数在块内一个数在零散部分的情况,询问时归并排序处理两个数都在零散部分的情况,时间复杂度$O((n+q)\sqrt{n})$ ...
- maven的包冲突
maven的间接引用会引入其他未声明的包,maven自身的冲突解决方案,最终引用的包可能不是希望的版本. 直接声明期望的版本号,就没有间接引用的问题. 子模块很多时,可以使用dependencyMan ...
- IKE协议
IKE协议 一. +IKE(Internet Key Exchange)因特网密钥交换协议 +为IPSec提供了自动协商交换密钥.建立安全联盟的服务 +通过数据交换来计算密钥 IKE(Internet ...
- [UE4]虚幻4的网络适合开发什么游戏
使用虚幻4开发网络游戏的两种方式 一.虚幻4只做客户端,服务器端独立开发,适用于任何网络游戏 二.使用虚幻4同时开发客户端和服务器(使用虚幻4内置的服务器),适用于一部分网络游戏. 如果使用虚幻4作为 ...
- [UE4]移除UI(User Widget)并销毁
1.移除UI,使用“Remove from Parent”方法 2.最后一步给UI变量赋值的时候,如果保持默认选择“Select Assets”,则会把UI变量销毁(赋值为null).
- [UE4]条件融合动画: Blend Posed by int
Aim Group=0:使用动画“Blend Pose 0” Aim Group=1:使用动画“Blend Pose 1”
- 解决在word中不能使用输入法
打开一个Word文档-------------->单击 文件---->选项---->高级---->取消什么?看图 然后重新启动word