Repository navigation
Correct pattern for only-once setup with eager app loading #2994
Unanswered
tlinhart
asked this question in
Potential Issue
Replies: 1 comment
|
PR #2919 deliberately imports the module once in the reloader parent for fail-fast validation, then imports it again in the spawned server process. An app factory prevents the parent from calling the factory, but it cannot make module-level side effects run only in the worker. Keep the imported module side-effect-free and move from contextlib import asynccontextmanager
import os
import debugpy
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app):
if os.getenv("DEBUG") == "1":
debugpy.listen(("127.0.0.1", 5678))
yield
def create_app():
return FastAPI(lifespan=lifespan)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:create_app", factory=True, reload=True)Uvicorn's reload path terminates and joins the old worker before starting the replacement, so the port is released between reloads. A fixed debugger port still cannot be shared by multiple simultaneous |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Hi, after merging this PR (#2919) when reloader is active, the app is loaded both in the parent process and in the worker, if I understand it correctly. In my setup I use an app factory pattern and in the main file create the app. Also, if
DEBUG=1env variable is set, I attach debugpy. However, now that the app is loaded twice, it leads to "address already in use" problem. What's the best way to solve this particular case?All reactions