CentOS 上 Python Web 框架选择与部署
一 选型建议
| 框架 | 典型场景 | 服务器/协议 | 主要优点 | 推荐人群 |
|---|---|---|---|---|
| Django | 复杂业务系统、后台管理、全栈项目 | WSGI:Gunicorn/uWSGI + Nginx | 内置 ORM/Admin/表单/认证,开发效率高 | 中大型团队、快速交付 |
| Flask | 轻量 API、微服务、原型验证 | WSGI:Gunicorn + Nginx | 灵活、扩展丰富、学习成本低 | 小团队、接口服务 |
| FastAPI | 高性能 API、异步 I/O | ASGI:Uvicorn/Hypercorn + Nginx | 基于类型提示、自动文档、并发能力强 | 高并发接口、实时服务 |
| Tornado | 长连接、WebSocket、异步服务 | 自带服务器或 ASGI | 非阻塞 I/O、适合实时场景 | 实时推送、长轮询 |
二 环境准备与基础安全
sudo yum install -y python3 python3-pippython3 -m venv venv && source venv/bin/activatepip install -r requirements.txt三 部署方案与命令示例
pip install gunicorngunicorn -w 4 -b 127.0.0.1:8000 myproject.wsgi:applicationserver {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /static/ {
alias /path/to/static/;
}
}
pip install fastapi uvicorn[standard]uvicorn main:app --host 127.0.0.1 --port 8000 --workers 4pip install uwsgiuwsgi --ini uwsgi.ini(配合 socket 与 Nginx 的 uwsgi_pass 使用)四 静态资源、数据库与缓存
/static/),Django 执行 collectstatic 集中资源;示例 Nginx 配置已包含 location /static/ 的 alias 指向。django-redis 配置默认缓存后端,提高读多写少场景性能。五 安全加固与运维实践
git pull、pip install -r requirements.txt、python manage.py collectstatic --noinput、python manage.py migrate、systemctl restart gunicorn 等步骤。