lifespan works not predictable, I think it should add some hooks. #11507
Replies: 3 comments 4 replies
-
Don't use lifespan and startup and shutdown events at one app. There is a remark about this in the FastAPI docs:
So, you need to move all you initialization logic into lifespan if you want to use it. There is a code example of intagration tortoise with FastAPI using lifespan in the documentation of tortoise: https://tortoise.github.io/examples/fastapi.html#main-py |
Beta Was this translation helpful? Give feedback.
-
I can not apply this documentation of tortoise: https://tortoise.github.io/examples/fastapi.html#main-py
|
Beta Was this translation helpful? Give feedback.
-
In addition, I have found an issue similar with mine. another issue. |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
I use a tortoise model in AuthenticationMiddleware, where JwtAuthMiddleware is customed by myself. But it report wrong as below.
I read some answer that says my tortoise-orm has not been initialized.
But if I delete the lifespan, it will works well. The code is below:
I study it seriously.
Reason:
Although My lifespan have not defined some logical. As the next generation of @app.on_event, the lifespan will change implement order:
before use lifespan:
init_connect(app) → register_middleware(app) → register_router(app) → register_exception(app)
after add lifespan parameter:
register_middleware(app) → register_router(app) →register_exception(app) → lifespan{ init_connect(app) }
That means lifespan function is executed after create_app().The serious problem is it will change @app.on_event("startup") functions execution time, which caused that the normal code will function unnormal.
register_tortoise is defined as below:
Operating System
Linux
Operating System Details
Ubuntu=20.04
tortoise-orm==0.20.0
fastapi==0.110.1
FastAPI Version
0.110.1
Pydantic Version
2.7.0
Python Version
3.10.14
Additional Context
I think lifespan should designed more exectact. I can add my logic at here, here.
Beta Was this translation helpful? Give feedback.
All reactions