GithubHelp home page GithubHelp logo

Comments (4)

vlakius avatar vlakius commented on May 26, 2024 3

I can confirm that I am using fastapi version 0.110.0 with tortoise orm 0.20.0 and lifespan.
The error NoneType' object is not iterable is due to the fact that the connection is not registered when you run the query

This is the solution I am currently using:

in my module: config_db.py

from contextlib import AbstractAsyncContextManager
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


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
        )
        print(f"Tortoise-ORM started, {connections._get_storage()}")
        if generate_schemas:
            print("Tortoise-ORM generating schema")
            await Tortoise.generate_schemas()

    async def close_orm() -> None:  # pylint: disable=W0612
        await connections.close_all()
        print("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()

in main.py

from contextlib import asynccontextmanager
from fastapi import FastAPI, Request

from .config_db import register_tortoise

@asynccontextmanager
async def lifespan(app: FastAPI):
   print("===========  Start REST API ===========")
    async with register_tortoise(
        app,
        db_url="sqlite://data.sqlite3",
        modules={"models": [__name__]},
        generate_schemas=True,
        add_exception_handlers=True,
    ):
        # your starting logic here...

        yield 
        print("===========  Stop REST API ===========")
        # your stop logic here


app = FastAPI(lifespan=lifespan)

from tortoise-orm.

qingshuiyuyu avatar qingshuiyuyu commented on May 26, 2024 2

thanks ,i got it @vlakius

from tortoise-orm.

sjtuli avatar sjtuli commented on May 26, 2024

I have created a discussion about this question.
tiangolo/fastapi#11507
From where I stand, the reason is lifespan will transform the function covered by @app.onevent("startup") .
the consequence is that these functions will run as soon as app have initialed.
BUT, these function might need run before some app-middleware applied, or need run after page logical function (such as this register_tortoise), SO I think fastapi should consider add some hooks to manage the life cycle.

from tortoise-orm.

daudln avatar daudln commented on May 26, 2024

Just a heads up, the PR #1541 addressing the Tortoise ORM v0.21.0 integration with FastAPI lifespan issue has been merged. 🎉 As a result, I'm going to go ahead and close the associated issue.

from tortoise-orm.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.