Comments (4)
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.
thanks ,i got it @vlakius
from tortoise-orm.
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.
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)
- model relationship bugged HOT 8
- why are there three files for one database? HOT 1
- auto_now not working HOT 2
- Field 'DatetimeField' has error when I use '__year' or '__month'. report this:" 'int' object has no attribute 'utcoffset' " HOT 2
- update(balance=Wallet.balance+1) how to do this? HOT 1
- Req: concurrent use of multiple databases HOT 2
- model.update_or_create KeyError HOT 3
- Bug: Pydantic 2.7 broke `pydantic_model_creator` HOT 7
- Occasionally during high-frequency queries, there may be differences between SQL statements and query results, leading to KeyError errors. Additionally, Command Out of Sync errors may also be reported during transactions
- QuerySet.count(): IndexError: list index out of range HOT 3
- ConnectionDoesNotExistError, connection was closed in the middle of operation
- Can not to use relation to table with unsigned pk HOT 2
- Documentation is completely broken - it points to the develop branch but says it's for 0.20.1 HOT 9
- Question - how to configure Tortoise for transparent auto-reconnect? HOT 2
- Doubts about the correctness of the result of the count() method HOT 3
- Add proper error messages and a doc page dedicated for testing HOT 3
- Support symmetrical ManyToMany relationships HOT 2
- Bulk Create without returning objects HOT 3
- OperationalError when attempting to filter by annotated field in m2m relation HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from tortoise-orm.