Tortoise-ORM FastAPI integration¶
We have a lightweight integration util tortoise.contrib.fastapi
which has a class RegisterTortoise
that can be used to set/clean up Tortoise-ORM in lifespan context.
FastAPI is basically Starlette & Pydantic, but in a very specific way.
See the FastAPI Examples & have a look at the Pydantic serialisation tutorials.
Reference¶
- class tortoise.contrib.fastapi.HTTPNotFoundError(**data)[source]¶
Bases:
BaseModel
- detail : str¶
-
model_computed_fields : ClassVar[Dict[str, ComputedFieldInfo]] =
{}
¶ A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
-
model_config : ClassVar[ConfigDict] =
{}
¶ Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
-
model_fields : ClassVar[Dict[str, FieldInfo]] =
{'detail': FieldInfo(annotation=str, required=True)}
¶ Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.
This replaces Model.__fields__ from Pydantic V1.
-
class tortoise.contrib.fastapi.RegisterTortoise(app=
None
, config=None
, config_file=None
, db_url=None
, modules=None
, generate_schemas=False
, add_exception_handlers=False
, use_tz=False
, timezone='UTC'
, _create_db=False
)[source]¶ Bases:
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 : Optional[FastAPI]¶
FastAPI app.
- config : Optional[dict]¶
Dict containing config:
Example
{ '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 : Optional[str]¶
Path to .json or .yml (if PyYAML installed) file containing config with same format as above.
- db_url : Optional[str]¶
Use a DB_URL string. See DB_URL
- modules : Optional[Dict[str, Iterable[Union[str, ModuleType]]]]¶
Dictionary of
key
: [list_of_modules
] that defined “apps” and modules that should be discovered for models.- generate_schemas : bool¶
True to generate schema immediately. Only useful for dev environments or SQLite
:memory:
databases- add_exception_handlers : bool¶
True to add some automatic exception handlers for
DoesNotExist
&IntegrityError
. This is not recommended for production systems as it may leak data.- use_tz : bool¶
A boolean that specifies if datetime will be timezone-aware by default or not.
- timezone : str¶
Timezone to use, default is UTC.
- Raises:¶
ConfigurationError – For any configuration error
-
tortoise.contrib.fastapi.register_tortoise(app, config=
None
, config_file=None
, db_url=None
, modules=None
, generate_schemas=False
, add_exception_handlers=False
)[source]¶ Registers
startup
andshutdown
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'¶
FastAPI app.
- config : Optional[dict]¶
Dict containing config:
Example
{ '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 : Optional[str]¶
Path to .json or .yml (if PyYAML installed) file containing config with same format as above.
- db_url : Optional[str]¶
Use a DB_URL string. See DB_URL
- modules : Optional[Dict[str, Iterable[Union[str, ModuleType]]]]¶
Dictionary of
key
: [list_of_modules
] that defined “apps” and modules that should be discovered for models.- generate_schemas : bool¶
True to generate schema immediately. Only useful for dev environments or SQLite
:memory:
databases- add_exception_handlers : bool¶
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
- Return type:¶
None