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 ...
随机推荐
- ssh config配置
使用ssh config文件可以简化ssh连接输入参数,直接从config读取 (1)建立config文件 config文件位置在~/.ssh/config 如果不存在,可以创建一个 (2)confi ...
- Java自定义数据验证注解Annotation
本文转载自:https://www.jianshu.com/p/616924cd07e6 Java注解Annotation用起来很方便,也越来越流行,由于其简单.简练且易于使用等特点,很多开发工具都提 ...
- [译] OpenStack Ocata 版本中的 53 个新功能盘点
原文链接:https://www.mirantis.com/blog/53-new-things-to-look-for-in-openstack-ocata/ 原文作者:Nick Chase, Ra ...
- 项目中自己一直用到的baseAdapter的类
import java.util.LinkedList; import java.util.List; import android.content.Context; import android.v ...
- JAVA Map 和 List 排序方法
private Map<String,String> mapDate; //正序 mapDate=new TreeMap<String, String>(new Compara ...
- Java中关于大小写字母的转换
方法一: 大小写字母在ascii码表中相减的值为32 故可将字符串转车字符数组 小写转大写减32 大写转小写加32 String s= "good"; char[] c = s.t ...
- FIN vs RST in TCP connections different
question: The way I understand this, there are 2 ways to close TCP connection: send FIN flag send RS ...
- css3凹角效果
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Conten ...
- U3D学习10——关节和射线检测
1.弹簧 2.铰链 3.固定关节 4.角色关节 5.自定义关节 6.raycast和raycasthit 射线有位移参数,可以设定只触发某一层的. 7.射线检测用于高速和精确 update是 ...
- ZooKeeper系列(9):ZooKeeper实现分布式Barrier和Queue
1. 快速开始 1.1概述: Zookeeper是Hadoop的一个子项目,它是分布式系统中的协调系统,可提供的服务主要有:配置服务.名字服务.分布式同步.组服务等. 1.2 使用常见 1.2.1 统 ...