FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful helpers to facilitate the completion of common tasks.
Installing
Install and update using pip:
$ pip install fastapi-sqlalchemy
Examples
Usage inside of a route
from fastapi import FastAPI
from fastapi_sqlalchemy import DBSessionMiddleware # middleware helper
from fastapi_sqlalchemy import db # an object to provide global access to a database session
from app.models import User
app = FastAPI()
app.add_middleware(DBSessionMiddleware, db_url="sqlite://")
# once the middleware is applied, any route can then access the database session
# from the global ``db``
@app.get("/users")
def get_users():
users = db.session.query(User).all()
return users
Note that the session object provided by db.session is based on the Python3.7+ ContextVar. This means that each session is linked to the individual request context in which it was created.
Usage outside of a route
Sometimes it is useful to be able to access the database outside the context of a request, such as in scheduled tasks which run in the background:
import pytz
from apscheduler.schedulers.asyncio import AsyncIOScheduler # other schedulers are available
from fastapi import FastAPI
from fastapi_sqlalchemy import db
from app.models import User, UserCount
app = FastAPI()
app.add_middleware(DBSessionMiddleware, db_url="sqlite://")
@app.on_event('startup')
async def startup_event():
scheduler = AsyncIOScheduler(timezone=pytz.utc)
scheduler.start()
scheduler.add_job(count_users_task, "cron", hour=0) # runs every night at midnight
def count_users_task():
"""Count the number of users in the database and save it into the user_counts table."""
# we are outside of a request context, therefore we cannot rely on ``DBSessionMiddleware``
# to create a database session for us. Instead, we can use the same ``db`` object and
# use it as a context manager, like so:
with db():
user_count = db.session.query(User).count()
db.session.add(UserCount(user_count))
db.session.commit()
# no longer able to access a database session once the db() context manager has ended
return users
Release files for FastAPI-SQLAlchemy 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| FastAPI-SQLAlchemy-0.2.1.tar.gz | 4.4 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| FastAPI_SQLAlchemy-0.2.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 10.1 kB
Release files / FastAPI-SQLAlchemy-0.2.1.tar.gz
| Download URL | FastAPI-SQLAlchemy-0.2.1.tar.gz |
|---|---|
| Size | 4.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7a9d44e46cbc73c3f5ee8c444f7e0bcd3d01370a878740abd4cd4d2e900ce9af
|
|
BLAKE2b-256 checksum How to use checksums |
d51dc08c99b2be52d822323840a7acc8f17df5bc3963e5e3431b4cedc0838b2f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.8.6
|
Release files / FastAPI_SQLAlchemy-0.2.1-py3-none-any.whl
| Download URL | FastAPI_SQLAlchemy-0.2.1-py3-none-any.whl |
|---|---|
| Size | 5.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d3bfc6d9388a73a2c3726bc6bd7764cd82debfa71c16e3991c544b9701f48d96
|
|
BLAKE2b-256 checksum How to use checksums |
0f8deb73397313152277934e6d9891786affe12704ddfb5a1ae1e9a869c98c53
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.49.0 CPython/3.8.6
|