Django+uwsgi+nginx 配置示例

环境信息

  • centos 7
  • Python 3.10
  • Django 4.0
  • uwsgi 2.0.20
  • nginx 1.20.1
  • venv

    示例中虚拟环境位于 /opt/vb/, Django工程目录位于 /opt/vb/vb/ , 工程名称为vb

uwsgi 配置文件 (uwsgi.ini) 配置示例

uwsgi.ini
[uwsgi]
socket = 127.0.0.1:8081
chdir = /opt/vb/vb
wsgi-file = ./vb/wsgi.py
master = true //主进程
vhost = true //多站模式
no-site = true //多站模式时不设置入口模块和文件
workers = 2 //子进程数
reload-mercy = 10
vacuum = true //退出、重启时清理文件
max-requests = 1000
limit-as = 512
buffer-size = 30000
pidfile = uwsgi-8081.pid
daemonize = uwsgi-8081.log
pythonpath = /opt/vb/env/lib/python3.10/site-packages/

启动 uwsgi 网关

uwsgi --ini uwsgi.ini

nginx 反带 uwsgi 配置文件示例

server {
listen 80;
server_name csms.tech;

location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8081;
uwsgi_param UWSGI_SCRIPT vb.wsgi;
uwsgi_param UWSGI_CHDIR /opt/vb/vb;
index index.html index.htm;
}
location /static/ {
alias /opt/vb/vb/staticCollects/;
}
access_log log/uwsgi.access.log main;
error_log log/uwsgi.error.log;
}

nginx 反带 Django 本地服务器配置示例

假设 Django 提供以下接口:

views.py
from django.http import JsonResponse

def debug_header(request):

keys_to_remove = ['XDG_SESSION_ID', 'SHELL', 'TERM', 'OLDPWD', 'HISTFILESIZE', 'USER', 'LS_COLORS', 'VIRTUAL_ENV', 'MAIL', 'PATH', 'PWD', 'LANG', 'wsgi.input', 'wsgi.errors', 'wsgi.file_wrapper', 'HISTSIZE', 'PS1', 'HISTCONTROL', 'SHLVL', 'HOME', 'LOGNAME', 'LESSOPEN', '_', 'DJANGO_SETTINGS_MODULE', 'RUN_MAIN', 'GATEWAY_INTERFACE', 'wsgi.version', 'wsgi.run_once', 'wsgi.multithread', 'wsgi.multiprocess']
headers = {key: value for key, value in request.META.items() if key not in keys_to_remove}
print(f"headers:{type(headers)}: {headers}")
# return HttpResponse(str(headers))
return JsonResponse(headers)

urls.py 内容如下:

urls.py
from django.contrib import admin
from django.urls import path
from .views import debug_header

urlpatterns = [
path('api/debug_header', debug_header),
path('admin/', admin.site.urls),
]

启动 Django server

python3 manage.py runserver 0.0.0.0:8888

要简单使用 Nginx 反带此 Django server,参考以下 Nginx 配置

server {
listen 80;
server_name api.domain.com;
access_log /home/logs/nginx/access/cs_api-access.log main;
location / {
proxy_pass http://172.31.1.8:8888/;
error_log /home/logs/nginx/error/api-error.log;


}
}

参考链接