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.5

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.5
File Size Uploaded Provenance Actions
FastAPI-SQLAlchemy-0.1.5.tar.gz 4.3 kB Without provenance Details for FastAPI-SQLAlchemy-0.1.5.tar.gz

Built distribution (wheel)

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

Total release size: 9.7 kB

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

Download URL FastAPI-SQLAlchemy-0.1.5.tar.gz
Size 4.3 kB
Tags Source
SHA-256 checksum
How to use checksums
67f6d101ca500c9ab9f4986e3daec110c72064381216a067eb06b127596f2210
BLAKE2b-256 checksum
How to use checksums
1ef42c71d580d666f50f8363f04ab2082c3f21ab35b0def0ffb80b233cc6ff18
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/49.2.0 requests-toolbelt/0.9.1 tqdm/4.48.0 CPython/3.8.5

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

Download URL FastAPI_SQLAlchemy-0.1.5-py3-none-any.whl
Size 5.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c2d22eaec16b9a5ebf0b4ed5614099b67391ba1d16aedbcb490fcfe8bb225b1f
BLAKE2b-256 checksum
How to use checksums
3c123f810de337ea49a746488da4441f007afd57721429851b7b83868a5a470d
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/49.2.0 requests-toolbelt/0.9.1 tqdm/4.48.0 CPython/3.8.5

Security for FastAPI-SQLAlchemy 0.1.5

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