用WSGI发布flask到centos7.9

起因

想把自己的Flask或者Django网站,发布到服务器上,让大家都可以访问。网上搜的结果,要么是用Nginx+uWSGI,要么是用Nginx+Gunicorn。大名鼎鼎的Nginx我早有耳闻,那么两位俩玩意是啥呢。

WSGI是什么

uwsgi是Nginx和web框架(比如flask和Django)之间的桥梁。Nginx处理静态文件非常优秀,却不能直接与我们的Python Web应用程序进行交互。flask或Django的测试服务器,处理并发效果很差。

为了解决Web 服务器与应用程序之间的交互问题,就出现了Web 服务器与应用程序之间交互的规范。最早出现的是CGI,后来又出现了改进 CGI 性能的FasgCGI,Java 专用的 Servlet 规范。在Python领域,最知名的就是WSGI规范了。

这其中,尤其以为uWSGI和Gunicorn最为有名

各自的优劣

那问题来了,二选一该选谁呢。

uwsgi目前好像只支持到比较低的版本,比如python3.8。这是因为我在python3.10的环境安装总是报错。后来网上冲浪了很久得出的答案。

Gunicorn,不支持windows。但好处是他安装简单,因为不依赖其他库。

python 复制代码
pip3 install gunicorn

gunicorn启动flask

python 复制代码
# 在虚拟环境安装一遍
pip install gunicorn #安装gunicorn
ln -s /usr/local/python3/bin/gunicorn /usr/bin/gunicorn #配置环境变量

启动项目

python 复制代码
# equivalent to 'from hello import app'
$ gunicorn -w 4 'main:app'

# equivalent to 'from hello import create_app; create_app()'
$ gunicorn -w 4 'main:create_app()'

可以指定端口

python 复制代码
gunicorn -w 4 -b 0.0.0.0:8080 'main:create_app()' #main文件下的app变量

用gunicorn关闭

python 复制代码
# 查看进程
pstree -ap|grep gunicorn
# 如果无法使用pstree命令,请yum安装
yum -y install psmisc

假如搜索结果如下:

通过如下命令杀进程:

python 复制代码
kill -HUP 76537

实际操作

下面举例说明如何操作

环境

centos7.9/Mysql8.0/Python3.10.10

首先默认以上都已OK,然后创建一个虚拟环境

python 复制代码
mkdir /opt/my_pj
cd /opt/my_pj
python3 -m venv venv310
# 进入虚拟环境的bin目录
cd py310\bin
# 启动虚拟环境
source activate

上传代码

通过git也好,ftp工具也好,将项目上传。例如我的项目叫hanayo,然后安装项目依赖

python 复制代码
pip install -r requirements.txt

当然还需要安装gunicorn

python 复制代码
pip install gunicorn

然后通过gunicorn启动项目,这里是在8080端口运行

python 复制代码
gunicorn -w 4 -b 0.0.0.0:8080 'hanayo:create_app()' #main文件下的app变量

这里我的代码中,hanayo是项目文件夹名,然后init文件中有create_app函数,这在Flask文档中好像叫工厂模式

Nginx简单设置

接下来设置nginx,yum安装的nginx,设置文件在/etc/nginx/nginx.conf

我这里设置在:/opt/nginx/conf/nginx.conf

python 复制代码
server {
    listen 80;
    server_name _;

    location / {
        proxy_pass http://127.0.0.1:8080/;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Prefix /;
    }
}

然后刷新nginx

python 复制代码
nginx -s reload

然后就大工告成啦!可以看到我的网站已经可以访问了

参考:

https://pythondjango.cn/python/tools/6-uwsgi-configuration/

https://dormousehole.readthedocs.io/en/latest/deploying/nginx.html

https://dormousehole.readthedocs.io/en/latest/deploying/gunicorn.html

相关推荐
sino爱学习2 分钟前
高性能线程池实践:Dubbo EagerThreadPool 设计与应用
java·后端
m0_715575343 分钟前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
甄心爱学习5 分钟前
【leetcode】判断平衡二叉树
python·算法·leetcode
深蓝电商API8 分钟前
滑块验证码破解思路与常见绕过方法
爬虫·python
Ulyanov10 分钟前
Pymunk物理引擎深度解析:从入门到实战的2D物理模拟全攻略
python·游戏开发·pygame·物理引擎·pymunk
颜酱14 分钟前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
掘金者阿豪17 分钟前
UUID的隐形成本:一个让数据库“慢下来”的陷阱
后端
sensen_kiss22 分钟前
INT303 Coursework1 爬取影视网站数据(如何爬虫网站数据)
爬虫·python·学习
用户0844652563730 分钟前
Docker 部署 MongoDB Atlas 到服务端
后端
玄同76538 分钟前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding