fastapi-sqlalchemy
fastapi-sqlalchemy copied to clipboard
Update README to include a more robust working example
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.
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 So the middleware actually does things like create_engine(), etc?
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