Skip to content
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

Closed
wu-clan opened this issue Apr 7, 2023 · 5 comments
Closed
Labels
enhancement New feature or request

Comments

@wu-clan
Copy link

wu-clan commented Apr 7, 2023

Describe the bug
when use lifespan with register_tortoise() in fastapi >= 0.95.0, register_tortoise() is not work

@waketzheng
Copy link
Contributor

waketzheng commented May 10, 2023

https://tortoise.github.io/examples/fastapi.html

This example worked with fastapi-0.95.1 and tortoise-orm-0.19.3

You may need to describe the bug with detail code @wu-clan

@long2ice long2ice added the enhancement New feature or request label May 11, 2023
@long2ice
Copy link
Member

Looks like lifespan can only pass into FastAPI when init

waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue May 16, 2023
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue May 17, 2023
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue May 17, 2023
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue May 20, 2023
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Jun 10, 2023
@waketzheng
Copy link
Contributor

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)

waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Sep 23, 2023
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
@i701
Copy link

i701 commented Sep 23, 2023

https://tortoise.github.io/examples/fastapi.html

This example worked with fastapi-0.95.1 and tortoise-orm-0.19.3

You may need to describe the bug with detail code @wu-clan

Does this example still work without getting missing created_at and updated_at fields error?

waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Sep 25, 2023
    2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Sep 25, 2023
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Sep 26, 2023
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Sep 26, 2023
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Sep 26, 2023
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Sep 27, 2023
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Sep 29, 2023
2. fix: pydantic v2 pydantic_model_creator nullable field not optional. (tortoise#1454)
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Oct 16, 2023
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Oct 20, 2023
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Nov 18, 2023
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Dec 30, 2023
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Jan 2, 2024
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Jan 2, 2024
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Jan 3, 2024
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Jan 5, 2024
waketzheng added a commit to waketzheng/tortoise-orm that referenced this issue Apr 27, 2024
@abondar
Copy link
Member

abondar commented May 24, 2024

Added lifespan support in 0.21.0

@abondar abondar closed this as completed May 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

5 participants