full-stack-fastapi-template icon indicating copy to clipboard operation
full-stack-fastapi-template copied to clipboard

fastapi and sqlalchemy

Open roshanafara opened this issue 2 years ago • 2 comments

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

roshanafara avatar Feb 16 '23 05:02 roshanafara

Are you using async or sync connection to database?

SarloAkrobata avatar Feb 16 '23 08:02 SarloAkrobata

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()

Vortexdude avatar Mar 07 '24 11:03 Vortexdude