mfreeborn / fastapi-sqlalchemy

Adds simple SQLAlchemy support to FastAPI
MIT License
594 stars 34 forks source link

Update README to include a more robust working example #15

Open mfreeborn opened 4 years ago

mfreeborn commented 4 years ago

The README example uses an in-memory SQLite database, which actually doesn't work properly off the bat. It would be better if the README contained a more complete example, at least using a persisted, file-based SQLite database.

mfreeborn commented 4 years ago

Done a bit more research; this is a minimally working example with an in-memory database:

from fastapi import FastAPI
from fastapi_sqlalchemy import DBSessionMiddleware, db
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.pool import StaticPool

app = FastAPI()
Base = declarative_base()

class User(Base):
    __tablename__ = "users"

    user_id = Column(Integer, primary_key=True)

# the following engine_args are required to make the in-memory database play nicely
app.add_middleware(
    DBSessionMiddleware,
    db_url="sqlite://",
    engine_args={"connect_args": {"check_same_thread": False}, "poolclass": StaticPool},
)

# need to create the database anew each time because it only exists in-memory
with db():
    Base.metadata.create_all(bind=db.session.get_bind())

# and now it will work in routes
@app.get("/users")
def get_users():
    users = db.session.query(User).all()
    return users

This is probably also very useful to know if setting up an environment for tests.

haveamission commented 2 years ago

@mfreeborn So the middleware actually does things like create_engine(), etc?

drewbroadley commented 1 year ago

Exactly what I was looking for in the example, the create_all() call. This is awesome.

Unfortunately I end up with:

No session found! Either you are not currently in a request context