Files
2021-09-17 15:14:36 +02:00

1.9 KiB

SQLAlchemy

FastAPI Users provides the necessary tools to work with SQL databases thanks to SQLAlchemy Core and encode/databases package for full async support.

Installation

Install the database driver that corresponds to your DBMS:

pip install 'databases[postgresql]'
pip install 'databases[mysql]'
pip install 'databases[sqlite]'

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

Setup User table

Let's declare our SQLAlchemy User table.

{!./src/db_sqlalchemy.py!}

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 tables

We'll now create an SQLAlchemy engine and ask it to create all the defined tables.

{!./src/db_sqlalchemy.py!}

!!! warning In production, it's strongly recommended to setup a migration system to update your SQL schemas. See Alembic.

Create the database adapter dependency

The database adapter of FastAPI Users makes the link between your database configuration and the users logic. It should be generated by a FastAPI dependency.

{!./src/db_sqlalchemy.py!}

Notice that we pass it three things:

  • A reference to your UserDB model.
  • A database instance, which allows us to do asynchronous request to the database.
  • The users variable, which is the actual SQLAlchemy table behind the table class.

What about SQLAlchemy ORM?

The primary objective was to use pure async approach as much as possible. However, we understand that ORM is convenient and useful for many developers. If this feature becomes very demanded, we will add a database adapter for SQLAlchemy ORM.