-
Notifications
You must be signed in to change notification settings - Fork 38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update README to include a more robust working example #15
Comments
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 |
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.
The text was updated successfully, but these errors were encountered: