Skip to main content

FastAPI-SQLAlchemy

https://github.com/mfreeborn/fastapi-sqlalchemy/workflows/ci/badge.svg https://codecov.io/gh/mfreeborn/fastapi-sqlalchemy/branch/master/graph/badge.svg https://img.shields.io/pypi/v/fastapi_sqlalchemy?color=blue

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

Metadata

Release files for FastAPI-SQLAlchemy 0.1.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for FastAPI-SQLAlchemy 0.1.4
File Size Uploaded Provenance Actions
FastAPI-SQLAlchemy-0.1.4.tar.gz 4.3 kB Without provenance Details for FastAPI-SQLAlchemy-0.1.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for FastAPI-SQLAlchemy 0.1.4
File Interpreter ABI Platform Actions
FastAPI_SQLAlchemy-0.1.4-py3-none-any.whl Python 3 none any Details for FastAPI_SQLAlchemy-0.1.4-py3-none-any.whl

Total release size: 9.7 kB

Release files / FastAPI-SQLAlchemy-0.1.4.tar.gz

Download URL FastAPI-SQLAlchemy-0.1.4.tar.gz
Size 4.3 kB
Tags Source
SHA-256 checksum
How to use checksums
65704b64c63ecf462f21d052355d43599fba6742b7731201fd8011120425d8ad
BLAKE2b-256 checksum
How to use checksums
a3c18732e6cd0c5c5958135419c415b9beb4a89149d431a352f03afb6ad07dec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.1.3 requests-toolbelt/0.9.1 tqdm/4.46.0 CPython/3.7.7

Release files / FastAPI_SQLAlchemy-0.1.4-py3-none-any.whl

Download URL FastAPI_SQLAlchemy-0.1.4-py3-none-any.whl
Size 5.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5434eb3159034185e49ff6bfe53df37be723bb62ccadb6efc79fb2e4fd63a99c
BLAKE2b-256 checksum
How to use checksums
ec4c65275f81826bd63864da24ba2b60ef96954667cff30651a40edc2d2d142a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.1.3 requests-toolbelt/0.9.1 tqdm/4.46.0 CPython/3.7.7

Security for FastAPI-SQLAlchemy 0.1.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page