'How to correctly use SQLalchemy within FastAPI or ARQ for MySQL?
I am using SQlalchemy for the database connection to a MySQL server in my FastAPI project, which consists of the actual API and a backend worker written using arq. Both share the same codebase, models and hence also the same database code.
I'm essentially creating the database connection like this:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import config as c
SQLALCHEMY_DATABASE_URL = "%s://%s:%s@%s:%d/%s" % (c.settings.db_type, c.settings.db_username, c.settings.db_password, c.settings.db_host, c.settings.db_port, c.settings.db_database)
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Which works most of the time. Every now and then however requests fail with the error message
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2006, "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))")
This however only happens in the worker part, haven't seen it in the FastAPI container yet, even though both are using the same code. In the arq tasks, whenever I need a database connection, I'm essentially doing:
from core.database import get_db
# ...
db = get_db().__next__()
Any ideas how to circumvent this issue? Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
