Skip to main content

SQLAlchemy middleware for FastAPI

Project description

SQLAlchemy FastAPI middleware

ci ci codecov License: MIT pip Downloads Updates

Description

Provides SQLAlchemy middleware for FastAPI using AsyncSession and async engine.

Install

  pip install fastapi-async-sqlalchemy

Important !!!

If you use sqlmodel install sqlalchemy<=1.4.41

Examples

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.

from fastapi import FastAPI
from fastapi_async_sqlalchemy import SQLAlchemyMiddleware
from fastapi_async_sqlalchemy import db  # provide access to a database session
from sqlalchemy import column
from sqlalchemy import table

app = FastAPI()
app.add_middleware(
    SQLAlchemyMiddleware,
    db_url="postgresql+asyncpg://user:user@192.168.88.200:5432/primary_db",
    engine_args={              # engine arguments example
        "echo": True,          # print all SQL statements
        "pool_pre_ping": True, # feature will normally emit SQL equivalent to “SELECT 1” each time a connection is checked out from the pool
        "pool_size": 5,        # number of connections to keep open at a time
        "max_overflow": 10,    # number of connections to allow to be opened above pool_size
    },
)
# once the middleware is applied, any route can then access the database session
# from the global ``db``

foo = table("ms_files", column("id"))

# Usage inside of a route
@app.get("/")
async def get_files():
    result = await db.session.execute(foo.select())
    return result.fetchall()

async def get_db_fetch():
    # It uses the same ``db`` object and use it as a context manager:
    async with db():
        result = await db.session.execute(foo.select())
        return result.fetchall()

# Usage inside of a route using a db context
@app.get("/db_context")
async def db_context():
    return await get_db_fetch()

# Usage outside of a route using a db context
@app.on_event("startup")
async def on_startup():
    # We are outside of a request context, therefore we cannot rely on ``SQLAlchemyMiddleware``
    # to create a database session for us.
    result = await get_db_fetch()


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8002)

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-async-sqlalchemy-0.5.0.tar.gz (5.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_async_sqlalchemy-0.5.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file fastapi-async-sqlalchemy-0.5.0.tar.gz.

File metadata

File hashes

Hashes for fastapi-async-sqlalchemy-0.5.0.tar.gz
Algorithm Hash digest
SHA256 41de6f84b6054657ee7fdbf5a96497c478fd2210f203b9442adc7d55ca95331e
MD5 54144257e6fb76b1fd81f859a6e76f67
BLAKE2b-256 72aa610363d8e64b7663756948761b17c76a9615c7d19a978dd3c83942f8671b

See more details on using hashes here.

File details

Details for the file fastapi_async_sqlalchemy-0.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_async_sqlalchemy-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9e571b9c023b393bbec94ce69a27783ca3d0705d72ae6525ae783631ddd5def8
MD5 87126531764beb8b4b93a757523b5be8
BLAKE2b-256 8381307cfb247cceb98567d2a0a2618b3e85cc1f04a60c646ef17b10b37bfe43

See more details on using hashes here.

Supported by

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