【python】flask、fastapi对比及部署差异

1,013 阅读1分钟

flask 是同步阻塞框架 fastapi 是异步非阻塞框架

如果直接 flask run 会报

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

这个警告, 解决方法是使用 gunicorn 来启动应用

gunicorn -w 4 'main:app'

上面的命令启动应用的同时也会开启4个线程

fastapi的启动方式则为

uvicorn main:app --port 5005

我也尝试使用uvicorn去启动 flask应用, 则直接报错

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/Users/blank/Library/Caches/pypoetry/virtualenvs/hello-FYQonWHQ-py3.10/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 408, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  File "/Users/blank/Library/Caches/pypoetry/virtualenvs/hello-FYQonWHQ-py3.10/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
    return await self.app(scope, receive, send)
  File "/Users/blank/Library/Caches/pypoetry/virtualenvs/hello-FYQonWHQ-py3.10/lib/python3.10/site-packages/uvicorn/middleware/asgi2.py", line 16, in __call__
    instance = self.app(scope)
TypeError: Flask.__call__() missing 1 required positional argument: 'start_response'
INFO:     127.0.0.1:52620 - "GET / HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/Users/blank/Library/Caches/pypoetry/virtualenvs/hello-FYQonWHQ-py3.10/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 408, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
  File "/Users/blank/Library/Caches/pypoetry/virtualenvs/hello-FYQonWHQ-py3.10/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__
    return await self.app(scope, receive, send)
  File "/Users/blank/Library/Caches/pypoetry/virtualenvs/hello-FYQonWHQ-py3.10/lib/python3.10/site-packages/uvicorn/middleware/asgi2.py", line 16, in __call__
    instance = self.app(scope)
TypeError: Flask.__call__() missing 1 required positional argument: 'start_response'
INFO:     127.0.0.1:52621 - "GET /favicon.ico HTTP/1.1" 500 Internal Server Error

应该是协议不兼容

尝试用 gunicorn 启动 fastapi 应用的话, 也会报错

[2023-10-05 18:16:12 +0800] [38568] [ERROR] Error handling request /
Traceback (most recent call last):
  File "/Users/blank/Library/Caches/pypoetry/virtualenvs/app-6mKjmJHg-py3.10/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 135, in handle
    self.handle_request(listener, req, client, addr)
  File "/Users/blank/Library/Caches/pypoetry/virtualenvs/app-6mKjmJHg-py3.10/lib/python3.10/site-packages/gunicorn/workers/sync.py", line 178, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
TypeError: FastAPI.__call__() missing 1 required positional argument: 'send'