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 ...
随机推荐
- maven私服的使用
使用的版本是nexus2 比较犀利的一个博客https://www.cnblogs.com/tyhj-zxp/p/7605879.html 一.安装搭建私服(windows) bin目录cmd执行ne ...
- HTTP/HLS/RTMP超级负载测试工具
这个负载测试工具是网游分享的工具,可以在http://blog.csdn.net/win_lin/article/details/11835011 或者https://github.com/winli ...
- bzoj4480: [Jsoi2013]快乐的jyy
[问题描述] 给定两个字符串A和B,表示JYY的两个朋友的名字.我们用A(i,j)表示A 字符串中从第i个字母到第j个字母所组成的子串.同样的,我们也可以定义B(x,y). JYY发现两个朋友关系的紧 ...
- 自定义鼠标右键(层叠式菜单:cascading menu)
Author:KillerLegend From:http://www.cnblogs.com/killerlegend/p/3575391.html Date:Tuesday, February 1 ...
- asp.net控件拖不动。控件错误
有一种可能是工程的存储路径名称不规范导致,更改命名空间及路径. 我的存储路径是C#文件夹下,去掉#完美解决
- 几个简单常用的jQuery实例
一.点赞效果: 1.1 效果: 1.2 代码: <!DOCTYPE html> <html lang="en"> <head> <meta ...
- [UE4]世界坐标、本地坐标
本地坐标 世界坐标
- FileMaker Server连接SQL Server测试
用FM测试了一把扫二维码.效果还不错,简单的设置几下就可以上线,使用Iphone扫二维码进行盘点以及更新照片功能.接下来测试下下ODBC连接. FMS连接SQL Server测试 1. 在FMS服务器 ...
- IDEA配置打可运行jar包
IDEA打包可以运行的jar包大体有两种方式:一种是比较方便的配置maven:一种是直接配置IDEA采用Build Artifacts打包. 配置maven打包,在pom.xml里面配置build插件 ...
- ext.net tooltip
业务场景:需要对grid表格中指定列显示tooltip. html: <form id="form1" runat="server"> <To ...