您的位置:首页 > 运维架构 > Nginx

django为什么线上部署的时候要用到 uwsgi 和 nginx

2018-09-14 11:52 267 查看

首先你要明确几个概念及其作用(注意大小写的区别):

  • WSGI
  • uWSGI
  • uwsgi
  • Nginx

WSGI 是一种协议,不是任何包不是任何服务器,就和 TCP 协议一样。它定义了 Web 服务器和 Web 应用程序之前如何通信的规范。

至于为什么和 Python 扯在一起?因为这个协议是由 Python 在 2003 年提出的。(参考:PEP-333 和 PEP-3333 )

WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request.

uWSGI 是一个全功能的 HTTP 服务器,他要做的就是把 HTTP 协议转化成语言支持的网络协议。比如把 HTTP 协议转化成 WSGI 协议,让 Python 可以直接使用。

The uWSGI project aims at developing a full stack for building hosting services.

Application servers (for various programming languages and protocols), proxies, process managers and monitors are all implemented using a common api and a common configuration style.

uwsgi 是一种 uWSGI 的内部协议,使用二进制方式和其他应用程序进行通信。

The uwsgi (lowercase!) protocol is the native protocol used by the uWSGI server.

It is a binary protocol that can carry any type of data. The first 4 bytes of a uwsgi packet describe the type of the data contained by the packet.

Nginx 是一个 Web 服务器其中的 HTTP 服务器功能和 uWSGI 功能很类似,但是 Nginx 还可以用作更多用途,比如最常用的反向代理功能。

所以用一张图来描述一下这个过程:

接下是为什么不能用 Django 的 Web 服务器直接部署

Django 是一个 Web 框架,框架的作用在于处理 request 和 response,其他的不是框架所关心的内容。所以怎么部署 Django 不是 Django 所需要关心的。

Django 所提供的是一个开发服务器,这个开发服务器,没有经过安全测试,而且使用的是 Python 自带的 simple HTTPServer 创建的,在安全性和效率上都是不行的。

DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests.

在 Django 源码中可以很清楚的看出来,runserver 起来的 HTTPServer 就是 Python 自带的 simple_server。

以下是最新版本 Django 有关 runserver command 的代码节选

其中 inner_run 函数中的 run 方法和 run 方法中 server_cls 参数分别取自 django.core.servers.basehttp:rundjango.core.servers.basehttp:WSGIServer

而 WSGIServer 又的父类就是 wsgiref.simple_server。既然是 simple 了很多东西都是不太可以的。

既然 uWSGI 可以完成 Nginx 功能,那为什么又要用 Nginx

因为 Nginx 牛逼啊,能直接在 Nginx 层面就完成很多事情,比如静态文件、反向代理、转发等需求。

参考

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: