如何上线Flask Web服务?

发布一下 0 0

Flask是Python编程中一款Web框架,因其开发高效且支持的插件丰富,使用比较广泛。这里聊一聊如何上线Flask开发的Web服务。Flask本身是内置Web服务的,不过它的性能不够强健,安全性也不高,官方仅推荐在开发或测试环境中使用,正式上线一般需配合Gunicorn或uWSGI,本文介绍使用Gunicorn和Nginx部署Flask Web服务。

环境介绍

操作系统:Debian 10.10

Python版本:3.7.3

代码准备

为了减少项目间的干扰,Python程序一般在虚拟环境中开发。

创建虚拟环境,

mkdir flask-examplecd flask-examplepython3 -m venv venv. venv/bin/activate

安装Gunicorn,

pip install gunicorn

样例程序flask-example/myapp.py,

from flask import Flaskapp = Flask(__name__)@app.route("/")def index():    return "hello world"if __name__ == "__main__":    app.run()

Gunicorn

使用Gunicorn创建WSGI入口点,文件flask-example/wsgi.py

from myapp import appif __name__ == "__main__":    app.run()

启动Gunicorn,

gunicorn --bind 0.0.0.0:5000 wsgi:app

上面命令管理Gunicorn比较麻烦,使用Systemd来管理,Unit服务文件如下,

[Unit]Description=Gunicorn instance to serve myappAfter=network.target[Service]User=aneirinGroup=aneirinWorkingDirectory=/home/aneirin/flask-exampleEnvironment="PATH=/home/aneirin/flask-example/venv/bin"ExecStart=/home/aneirin/flask-example/venv/bin/gunicorn --workers 3 --bind unix:myapp.sock -m 007 wsgi:app[Install]WantedBy=multi-user.target

开启三个工作线程,为了安全起见,设置了Gunicorn可写文件的umask为007。启动后,显示如下,

(venv) aneirin@debian-1:~/flask-example$ systemctl status myapp● myapp.service - Gunicorn instance to serve myapp   Loaded: loaded (/lib/systemd/system/myapp.service; disabled; vendor preset: enabled)   Active: active (running) since Sat 2022-09-10 21:35:53 HKT; 7min ago Main PID: 17542 (gunicorn)    Tasks: 4 (limit: 400)   Memory: 54.6M   CGroup: /system.slice/myapp.service           ├─17542 /home/aneirin/flask-example/venv/bin/python3 /home/aneirin/flask-example/venv/bin/gunicorn --workers 3 --bind unix:myapp.sock -m 007 wsgi:app           ├─17544 /home/aneirin/flask-example/venv/bin/python3 /home/aneirin/flask-example/venv/bin/gunicorn --workers 3 --bind unix:myapp.sock -m 007 wsgi:app           ├─17545 /home/aneirin/flask-example/venv/bin/python3 /home/aneirin/flask-example/venv/bin/gunicorn --workers 3 --bind unix:myapp.sock -m 007 wsgi:app           └─17546 /home/aneirin/flask-example/venv/bin/python3 /home/aneirin/flask-example/venv/bin/gunicorn --workers 3 --bind unix:myapp.sock -m 007 wsgi:app

可以看到主线程fork了三个工作线程。

Nginx

Web服务生产环境一般都使用Nginx作为反向代理,Nginx可以配置https,并有缓存功能,这里配置也很简单,加入下面配置文件,

server {    listen 80;    server_name example.xyz www.example.xyz;    location / {        include proxy_params;        proxy_pass http://unix:/home/aneirin/flask-example/myapp.sock;    }}

Nginx和Gunicorn的通信使用本地套接字文件效率比较高,当然也可以选择使用地址+端口的方式。如果需要使用https方式访问,可以在Lets Encrypt上申请免费的证书,这里不涉及了。

版权声明:内容来源于互联网和用户投稿 如有侵权请联系删除

本文地址:http://0561fc.cn/157249.html