Adds simple SQLAlchemy support to FastAPI
Project description
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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file FTSQLALCHEMY-0.2.1.tar.gz
.
File metadata
- Download URL: FTSQLALCHEMY-0.2.1.tar.gz
- Upload date:
- Size: 6.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.10.10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1f3016eebd83af277ae696c01d63ab1deaf0897b51fb4697431cac99974ed5d7 |
|
MD5 | ad7c163e0b689123a725dbb94a230971 |
|
BLAKE2b-256 | a02a9becbd2cf8ea5853ee61d4d6f63e185cf420f8a7d140b81dcd8c9a10d420 |
File details
Details for the file FTSQLALCHEMY-0.2.1-py3-none-any.whl
.
File metadata
- Download URL: FTSQLALCHEMY-0.2.1-py3-none-any.whl
- Upload date:
- Size: 5.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.0.0 CPython/3.10.10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1288413a20c370cfc0678ecbeb0d0055a5c04d12769d51a809565b819cf58d4a |
|
MD5 | d1f43decb8c9b2505f8b60357d1c7a0e |
|
BLAKE2b-256 | 486d5365925219aaf98ba562f8983d42f79ab51abb46b0110cfda9ff0a1c08b3 |