-
-
Notifications
You must be signed in to change notification settings - Fork 392
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
register_tortoise() is not compatible with lifespan in fastapis>=0.95.0 #1371
Comments
https://tortoise.github.io/examples/fastapi.html This example worked with You may need to describe the bug with detail code @wu-clan |
Looks like lifespan can only pass into FastAPI when init |
An example for tortoise-orm<=0.19.3 from contextlib import AbstractAsyncContextManager, asynccontextmanager
from types import ModuleType
from typing import Dict, Iterable, Optional, Union
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from tortoise import Tortoise, connections
from tortoise.exceptions import DoesNotExist, IntegrityError
from tortoise.log import logger
def register_tortoise(
app: FastAPI,
config: Optional[dict] = None,
config_file: Optional[str] = None,
db_url: Optional[str] = None,
modules: Optional[Dict[str, Iterable[Union[str, ModuleType]]]] = None,
generate_schemas: bool = False,
add_exception_handlers: bool = False,
) -> AbstractAsyncContextManager:
async def init_orm() -> None: # pylint: disable=W0612
await Tortoise.init(config=config, config_file=config_file, db_url=db_url, modules=modules)
logger.info("Tortoise-ORM started, %s, %s", connections._get_storage(), Tortoise.apps)
if generate_schemas:
logger.info("Tortoise-ORM generating schema")
await Tortoise.generate_schemas()
async def close_orm() -> None: # pylint: disable=W0612
await connections.close_all()
logger.info("Tortoise-ORM shutdown")
class Manager(AbstractAsyncContextManager):
async def __aenter__(self) -> "Manager":
await init_orm()
return self
async def __aexit__(self, *args, **kwargs) -> None:
await close_orm()
if add_exception_handlers:
@app.exception_handler(DoesNotExist)
async def doesnotexist_exception_handler(request: Request, exc: DoesNotExist):
return JSONResponse(status_code=404, content={"detail": str(exc)})
@app.exception_handler(IntegrityError)
async def integrityerror_exception_handler(request: Request, exc: IntegrityError):
return JSONResponse(
status_code=422,
content={"detail": [{"loc": [], "msg": str(exc), "type": "IntegrityError"}]},
)
return Manager()
@asynccontextmanager
async def lifespan(app: FastAPI):
# do sth before db inited
async with register_tortoise(
app,
db_url="sqlite://:memory:",
modules={"models": ["models"]},
generate_schemas=True,
add_exception_handlers=True,
):
# do sth while db connected
yield
# do sth after db closed
app = FastAPI(title="Tortoise ORM FastAPI example", lifespan=lifespan) |
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
Does this example still work without getting missing |
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
Added lifespan support in 0.21.0 |
Describe the bug
when use lifespan with register_tortoise() in fastapi >= 0.95.0, register_tortoise() is not work
The text was updated successfully, but these errors were encountered: