fastapi-sqlalchemy icon indicating copy to clipboard operation
fastapi-sqlalchemy copied to clipboard

Update README to include a more robust working example

Open mfreeborn opened this issue 4 years ago • 3 comments

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 avatar Jun 22 '20 12:06 mfreeborn

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.

mfreeborn avatar Jun 23 '20 09:06 mfreeborn

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

haveamission avatar Feb 17 '22 21:02 haveamission

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

drewbroadley avatar Oct 11 '22 06:10 drewbroadley