Stay Hungry,Stay Foolish!

pyinstaller package fastapi application with Gunicorn

使用 Gunicorn 部署 FastAPI 应用程序:快速而强大的组合

https://juejin.cn/post/7348003004123463717

本地部署

本地开发调试过程中,我通常是这样启动Fastapi服务的

在终端中运行:

 
uvicorn main:app --host 0.0.0.0 --port 80

当然,也可以python脚本启动:

 
import uvicorn
uvicorn.run(
    app="main:app",
    host="0.0.0.0",
    port=8088,
    reload=True
)

这样就好启动一个服务,reload=True支持热重载,方便调试。

应该是比较简单的,那到正式环境,为啥不使用uvicorn直接启动呢?是有更好的方式吗?

正式环境部署

在正式生产环境中,通常不直接使用 Uvicorn 来启动 FastAPI 应用,而是借助 Gunicorn 或者其他类似的 WSGI 服务器来处理请求。这是因为:

  • 性能和稳定性: Gunicorn 是一个专门用于生产环境部署的 WSGI 服务器,具有更好的性能和稳定性,能够处理大量并发请求并自动进行负载均衡。
  • 多进程支持: Gunicorn 支持多进程方式处理请求,通过调整 Worker 数量可以更好地利用多核 CPU 资源,提高并发处理能力。
  • 日志和监控: Gunicorn 提供了更丰富的日志记录功能,便于监控应用程序的运行情况,并支持与其他日志系统集成,有利于故障排查和性能优化。
  • 灵活性和扩展性: 使用 Gunicorn 可以方便地配置各种参数,调整工作模式、Worker 数量等,以适应不同规模和需求的应用程序。

终于引出了本文的主题,Gunicorn

Gunicorn

Gunicorn 是一个 Python WSGI HTTP 服务器,它允许运行Python的web应用程序。WSGI 是 Web Server Gateway Interface 的缩写,是 Python 应用程序与 Web 服务器之间的标准接口。

Gunicorn 的特点包括:

  • 易用性:只需一个简单的命令即可启动服务。
  • 兼容性:遵循 WSGI 标准,可以与大多数的Python web 框架协同工作。
  • 性能优化:使用预分叉模型来减少工作负载,并提高性能。
  • 并发处理:支持 gevent 和 asyncio 等异步工作模式,有效处理并发请求。

 

 

utils系列:pyinstaller 打包 以gunicorn启动的Flask

https://blog.csdn.net/qq_38284951/article/details/118249034

 

gunicorn with compiled python source

https://stackoverflow.com/questions/63242040/gunicorn-with-compiled-python-source

 

serving a gunicorn app with PyInstaller

https://github.com/benoitc/gunicorn/issues/669

from gunicorn.app.base import Application, Config
import gunicorn
from gunicorn import glogging
from gunicorn.workers import sync

class GUnicornFlaskApplication(Application):
    def __init__(self, app):
        self.usage, self.callable, self.prog, self.app = None, None, None, app

    def run(self, **options):
        self.cfg = Config()
        [self.cfg.set(key, value) for key, value in options.items()]
        return Application.run(self)

    load = lambda self:self.app


def app(environ, start_response):
    data = "Hello, World!\n"
    start_response("200 OK", [
        ("Content-Type", "text/plain"),
        ("Content-Length", str(len(data)))
    ])

    return iter(data)

if __name__ == "__main__":
    gunicorn_app = GUnicornFlaskApplication(app)
    gunicorn_app.run(
        worker_class="gunicorn.workers.sync.SyncWorker",
    )

 

posted @ 2025-01-23 16:49  lightsong  阅读(144)  评论(0)    收藏  举报
千山鸟飞绝,万径人踪灭