架构介绍
linux一般采用nginx + uwsgi部署django,在Windows下,可以取代uwsgi的选项包括Waitressa、Daphnea、Hypercoma和Gunicorna(通过WSLa 运行)。windows服务器一般采用nginx + waitress 部署django,,他们的关系如下
django是WEB应用框架,Nginx是web服务器,uwsgi或者waitress 是实现wsgi协议的东西。
django当然也可以python manage.py runserver 0.0.0.0:80来让外部访问,在生产环境中不推荐使用 Django 的 runserver
命令,主要有以下几个原因:
-
安全性问题:
-
runserver
是为开发和调试设计的,没有经过安全审计或性能测试。 -
它默认绑定在 0.0.0.0 地址上,对外网完全开放,可能会受到未授权访问的风险。
-
不支持 HTTPS,无法保证数据传输的安全性。
-
-
性能问题:
-
runserver
使用单线程处理请求,无法应对高并发场景。 -
它会为每个请求重新加载和执行 Django 应用程序,导致性能低下。
-
-
功能限制:
-
缺乏生产环境中需要的负载均衡和容错机制。
-
不支持静态文件的高效服务,通常需要借助专门的静态文件服务器(如 Nginx)。
-
-
替代方案:
-
在生产环境中,推荐使用专业的 Web 服务器(如 Nginx 或 Apache)搭配 WSGI 服务器(如 Gunicorn 或 uWSGI)来部署 Django 应用。
-
例如,可以使用 Nginx 作为反向代理服务器,将请求代理给 Gunicorn 来处理 Django 应用
-
windows下使用nginx + waitress 部署django
下载安装nginx和配置文件
1、下载
下载链接:nginx: download
一直都只在linux中使用nginx,还从未在windows中使用,感觉在windows中使用nginx更为简单
2、安装
下载的是一个压缩包,找个目录解压即可,无需安装,解压出来的内容为:
其中nginx.exe
是入口程序,不考虑系统命令的情况下,cd到当前目录,即可使用nginx的命令了:
Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-T : test configuration, dump it and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: NONE)
-e filename : set error log file (default: logs/error.log)
-c filename : set configuration file (default: conf/nginx.conf)
-g directives : set global directives out of configuration file
如果把nginx设置到环境变量中,即可在全局使用nginx
命令。
3、配置文件
和linux环境下配置一样,这里贴一份基础配置,主要是修改nginx目录下的conf/nginx.conf
:
worker_processes 2;error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;pid logs/nginx.pid;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';access_log logs/access.log main;sendfile on;keepalive_timeout 65;#gzip on;server {listen 80;server_name localhost 121.199.1.144;location / {proxy_set_header Host $host;proxy_pass http://127.0.0.1:8000;}location /static {alias C:\inetpub\wwwroot\sanxue\static;}location /media {alias C:\inetpub\wwwroot\sanxue\media;}
下载waitress和使用它
1、下载
pip install waitress
2、使用
waitress
的使用太简单了,国内使用的人也非常少,在django项目的根目录创建run.py
(文件名随意),内容如下:
from waitress import serve
from sanxue.wsgi import applicationserve(app=application,host='127.0.0.1',port=8000
)
然后使用命令行python run.py
即可启动django的服务了,比IIS
或apache
的简单太多了,跑个中小项目都不成问题。
如果想把以上的命令加到windwos服务中,可参考下面的第3点。
参考
1、waitress
官方文档https://docs.pylonsproject.org/projects/waitress/en/stable/index.html
2、如何在python web项目中使用waitress Run Python WSGI Web App with Waitress | DevDungeon
3、如何把python项目构建成windows服务 Run Python Script as Windows Service | DevDungeon