Skip to main content

Adds simple SQLModel support to FastAPI

Project description

FastAPI-SQLModel provides a simple integration between FastAPI and SQLModel 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-sqlmodel

Examples

Usage inside of a route

from fastapi import FastAPI
from fastapi_sqlmodel import DBSessionMiddleware  # middleware helper
from fastapi_sqlmodel 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_sqlmodel 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

FastAPI-SQLModel-0.0.1.tar.gz (5.1 kB view details)

Uploaded Source

Built Distribution

FastAPI_SQLModel-0.0.1-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

Details for the file FastAPI-SQLModel-0.0.1.tar.gz.

File metadata

  • Download URL: FastAPI-SQLModel-0.0.1.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

File hashes

Hashes for FastAPI-SQLModel-0.0.1.tar.gz
Algorithm Hash digest
SHA256 cd69134ffcf7ca393c57d39bb5c5855587a8436cb7528f5994071e1ca4615a47
MD5 9dd2d574b694565aadd3a31a848c5dc6
BLAKE2b-256 12f13ac23f5dc0a8d53cc37187c1aa768ecbe337bf6c969be61f8da760572a64

See more details on using hashes here.

File details

Details for the file FastAPI_SQLModel-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: FastAPI_SQLModel-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

File hashes

Hashes for FastAPI_SQLModel-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c3a53064b749f0646bc7e3759749076373f49daa38dbfd8c2f3679a7d7950837
MD5 54711a5835c19c07d31790bb996e16e6
BLAKE2b-256 d9a96290ebf66f087749d63c1ed7f2c427be7bb370c087801e318efc0b5496d4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page