4

My app with lifespan defined like this:

@contextlib.asynccontextmanager
async def lifespan(app:fa.FastAPI):
    print("LIFE SPAN: Start up")
    yield
    print("LIFE SPAN: Shutdown")
app_api = fa.FastAPI(lifespan=lifespan)

app_api.include_router(test.router)

inside retrofun/___main___.py .

from retrofun.api import app_api
import argparse
import uvicorn

def main():
    parser = argparse.ArgumentParser(
        description="Run the RetroFun application.")
    parser.add_argument(
        "-p", "--host-port", type=str, default="localhost:8000",
        help="Specify the host and port with format host:port (default: localhost:8000)")
    args = parser.parse_args()

    host,port=args.host_port.split(':')
    port = int(port)
    print(f"Starting retrofun at {args.host_port} ...")
    uvicorn.run(
        "retrofun.__main__:app_api",
        host=host,
        port=port,
        reload=True
    )

if __name__=="__main__":
    main()

Case 1: When I run python -m retrofun. Everything including lifespan works well.

Case 2: With docker file:

CMD ["uv","run","-m","retrofun","-p","0.0.0.0:5555"]

Everything works well like intent EXCEPT lifespan does not work (print to console) anymore.

Case 3: If i change the CMD in Dockerfile with another like:

CMD ["uv","run","fastapi","run","./src/retrofun/__main__.py"]

Lifespan works again.

Question: Why lifespan does not work in case 2 and how to resolve that? Thank you.

1 Answer 1

0

Try removing reload=True as the reload mechanism works by killing and restarting child processes. The lifespan startup/shutdown hooks are tied to the child processes, not the main process.

Also try running

CMD ["uv", "run", "retrofun.main:app_api", "--host", "0.0.0.0", "--port", "5555"]

instead of

CMD ["uv","run","-m","retrofun","-p","0.0.0.0:5555"]

because it directly tells uvicorn to import app_api as the FastAPI instance.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.