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命令分析的更多相关文章

  1. Django - Python3 常用命令

    1.创建Django 项目 执行命令 django-admin.py startproject project_name 2.创建app 执行命令 注意:要先进入项目目录下,cd project_na ...

  2. web 架构 /http协议,状态码,django中常用命令

    什么是web应用? web应用 架构 :B/S架构 | C/S架构 网站:BS架构其实就是应用程序: B是浏览器 S是sever(实现了wsgi协议,实现了socket的服务端) + applicat ...

  3. Django 自定义扩展命令

    import datetime import logger from django.conf import settings from django.db.models import Q from d ...

  4. Django manage.py 命令详解

    manage.py 查看命令的作用的语句 C:\Users\Administrator> python manage.py help Type 'manage.py help <subco ...

  5. MySQL中使用SHOW PROFILE命令分析性能的用法整理(配合explain效果更好,可以作为优化周期性检查)

    这篇文章主要介绍了MySQL中使用show profile命令分析性能的用法整理,show profiles是数据库性能优化的常用命令,需要的朋友可以参考下   show profile是由Jerem ...

  6. nohup 、&、 2>&1 命令分析

    nohup的意思是不间断的运行,&的意思是后台运行,2>&1的意思是标准输出和错误输出都重定向到同一个文件. 简单地说nohup运行时即使关掉控制台,它该运行还是运行. http ...

  7. 利用shell命令分析服务器日志

      在没有专业日志分析系统的情况下,我们有时需要对日志进行简单的分析,下面列出一些常用的shell命令分析日志的方法,一定要收藏 1.查看有多少个ip访问 awk '{print $1}' log_f ...

  8. linux日常常用命令分析

    日志处理: 测试网络路由: xargs使用方法: tcpdump命令分析: dd 写入磁盘测试 cpu个数: 查看网卡流量 查看端口联通情况,临时加端口 ntpdate同步: 可以取出变动的密码: 导 ...

  9. ffmpeg 转码并截图的命令分析

    一.转码并截图的命令分析: 1.转码并截图,将码率转换为900Kffmpeg -i E:\\1.MOV -i E:\\123.jpg -filter_complex overlay=W-w  -b:v ...

随机推荐

  1. IDEA创建简单servlet程序

    创建项目 创建完后的目录结构为: web项目配置 在WEB-INF目录下新建两个文件夹,分别命名未classes和lib(classes目录用于存放编译后的class文件,lib用于存放依赖的jar包 ...

  2. java中遍历实体类,获取属性名和属性值

    方式一(实体类): //java中遍历实体类,获取属性名和属性值 public static void testReflect(Object model) throws Exception{ for ...

  3. 关于oracle的sqlplus显示不完全的修改方法

    这样的显示看起来很痛苦 需要换行的时候没有进行换行,不需要换行的时候却进行了换行 参考的博客地址 https://blog.csdn.net/pan_tian/article/details/8059 ...

  4. 基于线程池的多并发Socket程序的实现

    Socket“服务器-客户端”模型的多线程并发实现效果的大体思路是:首先,在Server端建立“链接循环”,每一个链接都开启一个“线程”,使得每一个Client端都能通过已经建立好的线程来同时与Ser ...

  5. Jmeter(十六)Logic Controllers 之 Runtime Controller

    Runtime Controller-----运行时间控制器:控制其下的Sampler运行时间. 该控制器较为简单,官方文档也没作太多说明.照着Blazemeter写个例子: 运行,查看结果. 可以看 ...

  6. [UE4]旋转小地图

    一.Canvas Panel的旋转原点是Render Transform——>Pivot,Pivot坐标的取值范围是0到1,左上角的pivot坐标是[0,0],右下角的pivot坐标是[1,1] ...

  7. 【PHP】五分钟教你编写一个实时弹幕网站

    由于博主是个忠实的英雄联盟粉丝,所以经常观看一些明星大神的直播.而一谈到直播,肯定会看到满屏幕飘来飘去的弹幕.那么问题来了,这些视频弹幕网站如何做到实时同步的?PHP如何开发一个类似的网站? 首先要搞 ...

  8. 加入域的计算机重定向到指定的OU

    在我曾经呆过一个企业里,我们使用的是AD环境,计算机加入域时,我们需要使用一个单独的加域工具,里面有需要将计算机加入到指定OU的选项.所以每次加域我们都需要找个这个工具,实现加域过程.最后我发现其实最 ...

  9. Unreal Engine 4 Based Materials

    转自:http://www.52vr.com/article-862-1.html 材质参数   UE4的材质参数有4个,输入范围都是0~1之间……分别为:   Base Color Roughnes ...

  10. 第41课 kmp子串查找算法

    1. 朴素算法的改进 (1)朴素算法的优化线索 ①因为 Pa != Pb 且Pb==Sb:所以Pa != Sb:因此在Sd处失配时,子串P右移1位比较没有意义,因为前面的比较己经知道了Pa != Sb ...