full-stack-fastapi-template
full-stack-fastapi-template copied to clipboard
fastapi and sqlalchemy
In fast API after execution of the code, the database connection is not closing using SQL alchemy how to resolve this issue?
Are you using async or sync connection to database?
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()