FastAPI,uvicorn.run() 总是创建 3 个实例,但我想要 1 个实例

FastAPI, uvicorn.run() always create 3 instances, but I want it 1 instance

我 运行 在 PyCharm IDE 快速 API 并且它总是 运行 3 个工人。 我不知道为什么,但是,每次 API 调用都会访问最后创建的实例。

任何人都可以帮助我怎样才能得到单身运行宁工人?

代码:

import uvicorn
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from starlette.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(CORSMiddleware,
                   allow_origins=["*"],
                   allow_methods=["*"],
                   allow_headers=["*"])
print(f"main.py with :{app}")


@app.get('/')
def home():
    return "Hello"


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=False, log_level="debug", debug=True,
                workers=1, limit_concurrency=1, limit_max_requests=1)

控制台输出:

/Users/user/.pyenv/versions/3.7.10/bin/python /Users/user/github/my-project/backend/main.py
main.py with :<fastapi.applications.FastAPI object at 0x102b35d50>
INFO:     Will watch for changes in these directories: ['/Users/user/github/my-project/backend']
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [96259] using statreload
main.py with :<fastapi.applications.FastAPI object at 0x10daadf50>
main.py with :<fastapi.applications.FastAPI object at 0x1106bfe50>
INFO:     Started server process [96261]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

感谢您最后的评论,我更好地理解了您的问题。

你真正的问题

所以实际上你的问题是为什么 FastAPI 对象被创建了 3 次。

在日志中确实可以看到你有3个不同的内存地址0x102b35d500x10daadf500x1106bfe50

这并不意味着您有 3 个工人,只是 FastAPI 对象被创建了 3 次。最后一个是您的 API 将使用的那个。

为什么会这样

对象被多次创建,因为:

  1. 首先,你 运行 main.py 遍历所有代码(一次创建 FastAPI 对象),然后到达 __main__
  2. 然后 uvicorn 启动 main:app 所以它再次转到文件 main.py 并构建另一个 FastAPI 对象。
  3. 最后一个由 debug=True 创建,当您将其设置为 False 时,您会少创建一个 FastAPI 对象。我不太清楚为什么。

解决方法

解决方案是将 API 定义与 API 的开头分开。

例如,可以创建一个 run.py 文件:

import uvicorn

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=False, log_level="debug", debug=True,
                workers=1, limit_concurrency=1, limit_max_requests=1)

并启动这个文件。

另一种选择是在命令行中启动 API:

uvicorn main:app --host=0.0.0.0 --port=8000 --log-level=debug --limit-max-requests=1 --limit-concurrency=1

您可以找到所有命令行参数here