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

fastapi and sqlalchemy #499

Open
roshanafara opened this issue Feb 16, 2023 · 2 comments
Open

fastapi and sqlalchemy #499

roshanafara opened this issue Feb 16, 2023 · 2 comments

Comments

@roshanafara
Copy link

In fast API after execution of the code, the database connection is not closing using SQL alchemy how to resolve this issue?

@SarloAkrobata
Copy link

Are you using async or sync connection to database?

@Vortexdude
Copy link

you could try something like this -

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
session = SessionLocal()
user = session.query(Model).filter_by(user_id=1).first()
session.close()

or ref - https://docs.sqlalchemy.org/en/20/orm/quickstart.html#declare-models:~:text=Database%20Metadata.-,Create%20Objects%20and%20Persist,-%C2%B6

from sqlalchemy.orm import Session

with Session(engine) as session:
    spongebob = User(
        name="spongebob",
        fullname="Spongebob Squarepants",
        addresses=[Address(email_address="[email protected]")],
    )
    sandy = User(
        name="sandy",
        fullname="Sandy Cheeks",
        addresses=[
            Address(email_address="[email protected]"),
            Address(email_address="[email protected]"),
        ],
    )
    patrick = User(name="patrick", fullname="Patrick Star")
    session.add_all([spongebob, sandy, patrick])
    session.commit()

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