Tortoise-ORM Starlette integration¶
We have a lightweight integration util tortoise.contrib.starlette, which includes a synchronous function register_tortoise that sets up Tortoise-ORM on startup and cleans it up on teardown, along with a class RegisterTortoise that can be used to set up and clean up Tortoise-ORM within a lifespan context.
See the Starlette Example
Reference¶
-
class tortoise.contrib.starlette.RegisterTortoise(app, config=
None, config_file=None, db_url=None, modules=None, generate_schemas=False, use_tz=True, timezone='UTC', _create_db=False, _enable_global_fallback=True)[source]¶ Bases:
AbstractAsyncContextManager
-
tortoise.contrib.starlette.register_tortoise(app, config=
None, config_file=None, db_url=None, modules=None, generate_schemas=False)[source]¶ Registers
startupandshutdownevents to set-up and tear-down Tortoise-ORM inside a Starlette application.You can configure using only one of
config,config_fileand(db_url, modules).- Parameters:¶
- app : Starlette¶
Starlette app.
- config : dict | None¶
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 : str | None¶
Path to .json or .yml (if PyYAML installed) file containing config with same format as above.
- db_url : str | None¶
Use a DB_URL string. See DB_URL
- modules : dict[str, Iterable[str | ModuleType]] | None¶
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
- Raises:¶
ConfigurationError – For any configuration error
- Return type:¶
None