» Python:使用Flask构建REST API » 3. 部署 » 3.1 WSGI: Gunicorn

WSGI:Gunicorn

一旦完成应用程序的开发,你可能需要将其部署以供公开访问。在本地开发期间,你可以依赖 Flask 自带的开发服务器、调试器和重载器,但这些不适用于生产环境。你需要选择一个专用的 WSGI 服务器或托管平台。

Flask 应用都是 WSGI 应用。WSGI 服务器用于运行这种应用程序,将传入的 HTTP 请求转换为标准的 WSGI 环境请求,并将传出的 WSGI 响应转换为 HTTP 响应。

使用 Gunicorn

Gunicorn

Gunicorn 是一个纯 Python 实现的 WSGI 服务器。它配置简单,通过多个工作进程实现性能调优。

安装 gunicorn

pip3 install gunicorn

使用 gunicorn 运行程序

gunicorn -w 4 -b :5000 main:app

如果需要看日志,添加 --log-level debug 标记选项。

-w 选项指定工作进程数;起始值一般是 CPU * 2

-b 选项将 Gunicorn 绑定监听 5000 端口。

main:app 表示模块名和主应用变量名。main 是 Python 文件 (main.py) 的名称;app 是承载 Flask 应用的变量的名称。

确保你的 config.ymlmain.py 在同一级目录,且所有数据库都是启动就绪的状态。

Gunicorn 启动日志大致如下:

[2024-03-08 22:16:31 +0800] [75236] [INFO] Starting gunicorn 21.2.0
[2024-03-08 22:16:31 +0800] [75236] [INFO] Listening at: http://0.0.0.0:5000 (75236)
[2024-03-08 22:16:31 +0800] [75236] [INFO] Using worker: sync
[2024-03-08 22:16:31 +0800] [75238] [INFO] Booting worker with pid: 75238
[2024-03-08 22:16:31 +0800] [75239] [INFO] Booting worker with pid: 75239
[2024-03-08 22:16:31 +0800] [75240] [INFO] Booting worker with pid: 75240
[2024-03-08 22:16:31 +0800] [75241] [INFO] Booting worker with pid: 75241

curl 发送一些请求过去。

curl -X GET "http://localhost:5000/books?o=5"

响应中能看到如下内容:

[{"author":"Jane Austen","created_at":"2024-03-02T05:48:25","description":"A classic novel exploring the themes of love, reputation, and social class in Georgian England.","id":7,"isbn":"9780486284736","published_at":"1813-01-28","title":"Pride and Prejudice","total_pages":279,"updated_at":"2024-03-02T05:48:25"},{"author":"J.D. Salinger","created_at":"2024-03-02T05:48:25","description":"A novel narrated by a disaffected teenager, exploring themes of alienation and identity.","id":8,"isbn":"9780316769488","published_at":"1951-07-16","title":"The Catcher in the Rye","total_pages":277,"updated_at":"2024-03-02T05:48:25"},{"author":"J.R.R. Tolkien","created_at":"2024-03-02T05:48:25","description":"A high fantasy epic following the quest to destroy the One Ring and defeat the Dark Lord Sauron.","id":9,"isbn":"9780544003415","published_at":"1954-07-29","title":"The Lord of the Rings","total_pages":1178,"updated_at":"2024-03-02T05:48:25"},{"author":"Herman Melville","created_at":"2024-03-02T05:48:25","description":"A novel exploring themes of obsession, revenge, and the nature of good and evil.","id":10,"isbn":"9780142000083","published_at":"1851-10-18","title":"Moby-Dick","total_pages":624,"updated_at":"2024-03-02T05:48:25"},{"author":"J.R.R. Tolkien","created_at":"2024-03-02T05:48:25","description":"A fantasy novel set in Middle-earth, following the adventure of Bilbo Baggins and the quest for treasure.","id":11,"isbn":"9780345339683","published_at":"1937-09-21","title":"The Hobbit","total_pages":310,"updated_at":"2024-03-02T05:48:25"}]

干得漂亮!⭐️

上页下页