+
+ + +
+
+
+ +
+
+
+ + +
+
+
+ + +
+
+
+ + +
+
+ + + +

Tortoise ORM

+

FastAPI Users provides the necessary tools to work with Tortoise ORM.

+

Installation

+

Install the database driver that corresponds to your DBMS:

+
pip install asyncpg
+
+ +
pip install aiomysql
+
+ +
pip install aiosqlite
+
+ +

For the sake of this tutorial from now on, we'll use a simple SQLite databse.

+

Setup User table

+

Let's declare our User model.

+
from fastapi import FastAPI
+from fastapi_users.db.tortoise import BaseUserModel, TortoiseUserDatabase
+from tortoise import Model
+from tortoise.contrib.starlette import register_tortoise
+
+DATABASE_URL = "sqlite://./test.db"
+
+
+class UserModel(BaseUserModel, Model):
+    pass
+
+
+user_db = TortoiseUserDatabase(UserModel)
+app = FastAPI()
+
+register_tortoise(app, modules={"models": ["path_to_your_package"]})
+
+ +

As you can see, FastAPI Users provides a mixin that will include base fields for our User table. You can of course add you own fields there to fit to your needs!

+

Create the database adapter

+

The database adapter of FastAPI Users makes the link between your database configuration and the users logic. Create it like this.

+
from fastapi import FastAPI
+from fastapi_users.db.tortoise import BaseUserModel, TortoiseUserDatabase
+from tortoise import Model
+from tortoise.contrib.starlette import register_tortoise
+
+DATABASE_URL = "sqlite://./test.db"
+
+
+class UserModel(BaseUserModel, Model):
+    pass
+
+
+user_db = TortoiseUserDatabase(UserModel)
+app = FastAPI()
+
+register_tortoise(app, modules={"models": ["path_to_your_package"]})
+
+ +

Register Tortoise

+

For using Tortoise ORM we must register our models and database.

+

Tortoise ORM supports integration with Starlette/FastAPI out-of-the-box. It will automatically bind startup and shutdown events.

+
from fastapi import FastAPI
+from fastapi_users.db.tortoise import BaseUserModel, TortoiseUserDatabase
+from tortoise import Model
+from tortoise.contrib.starlette import register_tortoise
+
+DATABASE_URL = "sqlite://./test.db"
+
+
+class UserModel(BaseUserModel, Model):
+    pass
+
+
+user_db = TortoiseUserDatabase(UserModel)
+app = FastAPI()
+
+register_tortoise(app, modules={"models": ["path_to_your_package"]})
+
+ +

Next steps

+

We will now configure an authentication method.

+ + + + + + + + + +
+
+
+