PHP前端开发

分析Python的Django框架的运行方式及处理流程

百变鹏仔 1天前 #Python
文章标签 框架

之前在网上看过一些介绍django处理请求的流程和django源码结构的文章,觉得了解一下这些内容对开发django项目还是很有帮助的。所以,我按照自己的逻辑总结了一下django项目的运行方式和对request的基本处理流程。


一、Django的运行方式

运行Django项目的方法很多,这里主要介绍一下常用的方法。一种是在开发和调试中经常用到runserver方法,使用Django自己的web server;另外一种就是使用fastcgi,uWSGIt等协议运行Django项目,这里以uWSGIt为例。

1、runserver方法

runserver方法是调试Django时经常用到的运行方式,它使用Django自带的WSGI Server运行,主要在测试和开发中使用,使用方法如下:

Usage: manage.py runserver [options] [optional port number, or ipaddr:port]# python manager.py runserver  # default port is 8000# python manager.py runserver 8080# python manager.py runserver 127.0.0.1:9090

看一下manager.py的源码,你会发现上面的命令其实是通过Django的execute_from_command_line方法执行了内部实现的runserver命令,那么现在看一下runserver具体做了什么。。

看了源码之后,可以发现runserver命令主要做了两件事情:

立即学习“Python免费学习笔记(深入)”;

    1). 解析参数,并通过django.core.servers.basehttp.get_internal_wsgi_application方法获取wsgi handler;

    2). 根据ip_address和port生成一个WSGIServer对象,接受用户请求

get_internal_wsgi_application的源码如下:def get_internal_wsgi_application():  """  Loads and returns the WSGI application as configured by the user in  ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,  this will be the ``application`` object in ``projectname/wsgi.py``.   This function, and the ``WSGI_APPLICATION`` setting itself, are only useful  for Django's internal servers (runserver, runfcgi); external WSGI servers  should just be configured to point to the correct application object  directly.   If settings.WSGI_APPLICATION is not set (is ``None``), we just return  whatever ``django.core.wsgi.get_wsgi_application`` returns.   """  from django.conf import settings  app_path = getattr(settings, 'WSGI_APPLICATION')  if app_path is None:    return get_wsgi_application()   return import_by_path(    app_path,    error_prefix="WSGI application '%s' could not be loaded; " % app_path  )

通过上面的代码我们可以知道,Django会先根据settings中的WSGI_APPLICATION来获取handler;在创建project的时候,Django会默认创建一个wsgi.py文件,而settings中的WSGI_APPLICATION配置也会默认指向这个文件。看一下这个wsgi.py文件,其实它也和上面的逻辑一样,最终调用get_wsgi_application实现。

2、uWSGI方法

uWSGI+Nginx的方法是现在最常见的在生产环境中运行Django的方法,本人的博客也是使用这种方法运行,要了解这种方法,首先要了解一下WSGI和uWSGI协议。

WSGI,全称Web Server Gateway Interface,或者Python Web Server Gateway Interface,是为Python语言定义的Web服务器和Web应用程序或框架之间的一种简单而通用的接口,基于现存的CGI标准而设计的。WSGI其实就是一个网关(Gateway),其作用就是在协议之间进行转换。(PS: 这里只对WSGI做简单介绍,想要了解更多的内容可自行搜索)

uWSGI是一个Web服务器,它实现了WSGI协议、uwsgi、http等协议。注意uwsgi是一种通信协议,而uWSGI是实现uwsgi协议和WSGI协议的Web服务器。uWSGI具有超快的性能、低内存占用和多app管理等优点。以我的博客为例,uWSGI的xml配置如下:

<uwsgi><!-- 端口 --><socket>:7600</socket><stats>:40000</stats><!-- 系统环境变量 --><env>DJANGO_SETTINGS_MODULE=geek_blog.settings</env><!-- 指定的python WSGI模块 --><module>django.core.handlers.wsgi:WSGIHandler()</module><processes>6</processes><master></master><master-as-root></master-as-root><!-- 超时设置 --><harakiri>60</harakiri><harakiri-verbose></harakiri-verbose><daemonize>/var/app/log/blog/uwsgi.log</daemonize><!-- socket的监听队列大小 --><listen>32768</listen><!-- 内部超时时间 --><socket-timeout>60</socket-timeout></uwsgi>