[docs]classRegisterTortoise(AbstractAsyncContextManager):""" Registers Tortoise-ORM with set-up and tear-down inside a FastAPI application's lifespan. You can configure using only one of ``config``, ``config_file`` and ``(db_url, modules)``. Parameters ---------- app: FastAPI app. config: Dict containing config: Example ------- .. code-block:: python3 { 'connections': { # Dict format for connection 'default': { 'engine': 'tortoise.backends.asyncpg', 'credentials': { 'host': 'localhost', 'port': '5432', 'user': 'tortoise', 'password': 'qwerty123', 'database': 'test', } }, # Using a DB_URL string 'default': 'postgres://postgres:qwerty123@localhost:5432/events' }, 'apps': { 'models': { 'models': ['__main__'], # If no default_connection specified, defaults to 'default' 'default_connection': 'default', } } } config_file: Path to .json or .yml (if PyYAML installed) file containing config with same format as above. db_url: Use a DB_URL string. See :ref:`db_url` modules: Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that should be discovered for models. generate_schemas: True to generate schema immediately. Only useful for dev environments or SQLite ``:memory:`` databases add_exception_handlers: True to add some automatic exception handlers for ``DoesNotExist`` & ``IntegrityError``. This is not recommended for production systems as it may leak data. use_tz: A boolean that specifies if datetime will be timezone-aware by default or not. timezone: Timezone to use, default is UTC. Raises ------ ConfigurationError For any configuration error """def__init__(self,app:Optional[FastAPI]=None,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,use_tz:bool=False,timezone:str="UTC",_create_db:bool=False,)->None:self.app=appself.config=configself.config_file=config_fileself.db_url=db_urlself.modules=modulesself.generate_schemas=generate_schemasself.use_tz=use_tzself.timezone=timezoneself._create_db=_create_dbifadd_exception_handlersandappisnotNone:@app.exception_handler(DoesNotExist)asyncdefdoesnotexist_exception_handler(request:"Request",exc:DoesNotExist):returnJSONResponse(status_code=404,content={"detail":str(exc)})@app.exception_handler(IntegrityError)asyncdefintegrityerror_exception_handler(request:"Request",exc:IntegrityError):returnJSONResponse(status_code=422,content={"detail":[{"loc":[],"msg":str(exc),"type":"IntegrityError"}]},)
[docs]defregister_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,)->None:""" Registers ``startup`` and ``shutdown`` events to set-up and tear-down Tortoise-ORM inside a FastAPI application. You can configure using only one of ``config``, ``config_file`` and ``(db_url, modules)``. Parameters ---------- app: FastAPI app. config: Dict containing config: Example ------- .. code-block:: python3 { 'connections': { # Dict format for connection 'default': { 'engine': 'tortoise.backends.asyncpg', 'credentials': { 'host': 'localhost', 'port': '5432', 'user': 'tortoise', 'password': 'qwerty123', 'database': 'test', } }, # Using a DB_URL string 'default': 'postgres://postgres:qwerty123@localhost:5432/events' }, 'apps': { 'models': { 'models': ['__main__'], # If no default_connection specified, defaults to 'default' 'default_connection': 'default', } } } config_file: Path to .json or .yml (if PyYAML installed) file containing config with same format as above. db_url: Use a DB_URL string. See :ref:`db_url` modules: Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that should be discovered for models. generate_schemas: True to generate schema immediately. Only useful for dev environments or SQLite ``:memory:`` databases add_exception_handlers: True to add some automatic exception handlers for ``DoesNotExist`` & ``IntegrityError``. This is not recommended for production systems as it may leak data. Raises ------ ConfigurationError For any configuration error """orm=RegisterTortoise(app,config,config_file,db_url,modules,generate_schemas,add_exception_handlers,)ifisinstance(lifespan:=app.router.lifespan_context,_DefaultLifespan):# Leave on_event here to compare with old versions# So people can upgrade tortoise-orm in running project without changing any code@app.on_event("startup")asyncdefinit_orm()->None:# pylint: disable=W0612awaitorm.init_orm()@app.on_event("shutdown")asyncdefclose_orm()->None:# pylint: disable=W0612awaitorm.close_orm()else:# If custom lifespan was passed to app, register tortoise in itwarnings.warn("`register_tortoise` function is deprecated, ""use the `RegisterTortoise` class instead.""See more about it on https://tortoise.github.io/examples/fastapi",DeprecationWarning,)@asynccontextmanagerasyncdeform_lifespan(app_instance:"FastAPI"):asyncwithorm:asyncwithlifespan(app_instance):yieldapp.router.lifespan_context=orm_lifespan