Skip to content
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

Open
mfreeborn opened this issue Jun 22, 2020 · 3 comments
Open

Update README to include a more robust working example #15

mfreeborn opened this issue Jun 22, 2020 · 3 comments

Comments

@mfreeborn
Copy link
Owner

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
Copy link
Owner Author

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
Copy link

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

@drewbroadley
Copy link

drewbroadley commented Oct 11, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants