起因

想把自己的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。但好处是他安装简单,因为不依赖其他库。

pip3 install gunicorn

用gunicorn启动flask

# 在虚拟环境安装一遍

pip install gunicorn #安装gunicorn

ln -s /usr/local/python3/bin/gunicorn /usr/bin/gunicorn #配置环境变量

启动项目

# 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()'

可以指定端口

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

用gunicorn关闭

# 查看进程

pstree -ap|grep gunicorn

# 如果无法使用pstree命令,请yum安装

yum -y install psmisc

假如搜索结果如下:

通过如下命令杀进程:

kill -HUP 76537

实际操作

下面举例说明如何操作

环境

centos7.9/Mysql8.0/Python3.10.10

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

mkdir /opt/my_pj

cd /opt/my_pj

python3 -m venv venv310

# 进入虚拟环境的bin目录

cd py310\bin

# 启动虚拟环境

source activate

上传代码

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

pip install -r requirements.txt

当然还需要安装gunicorn

pip install gunicorn

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

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

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的具体各个配置是什么意思,这里不做说明。我的理解是,我的flask运行在8080端口上,而nginx监听服务器的80端口,这就捕获到了对这台服务器的web请求,然后nginx会把所有请求转发到本机的8080端口上,从而实现了在Internet上访问我们的flask项目。

然后刷新nginx

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

相关阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: