Files
fastapi-users/docs/configuration/databases/sqlalchemy.md
François Voron c4de66b81c Revamp authentication (#831)
* Implement Transport classes

* Implement authentication strategy classes

* Revamp authentication with Transport and Strategy

* Revamp strategy and OAuth so that they can use a callable dependency

* Update docstring

* Make ErrorCode a proper Enum and cleanup unused OpenAPI utils

* Remove useless check

* Tweak typing in authenticator

* Update docs

* Improve logout/destroy token logic

* Update docs

* Update docs

* Update docs and full examples

* Apply formatting to examples

* Update OAuth doc and examples

* Add migration doc

* Implement Redis session token

* Add Redis Session documentation

* RedisSession -> Redis

* Fix links in docs
2021-12-30 15:22:07 +01:00

61 lines
1.9 KiB
Markdown

# SQLAlchemy
**FastAPI Users** provides the necessary tools to work with SQL databases thanks to [SQLAlchemy Core](https://docs.sqlalchemy.org/en/13/core/) and [encode/databases](https://www.encode.io/databases/) package for full async support.
## Installation
Install the database driver that corresponds to your DBMS:
```sh
pip install 'databases[postgresql]'
```
```sh
pip install 'databases[mysql]'
```
```sh
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.
```py hl_lines="13 14"
--8<-- "docs/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.
```py hl_lines="17 18 19 20"
--8<-- "docs/src/db_sqlalchemy.py"
```
!!! warning
In production, it's strongly recommended to setup a migration system to update your SQL schemas. See [Alembic](https://alembic.sqlalchemy.org/en/latest/).
## 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.
```py hl_lines="25 26"
--8<-- "docs/src/db_sqlalchemy.py"
```
Notice that we pass it three things:
* A reference to your [`UserDB` model](../models.md).
* 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.