I’m having a problem where I make 2 or 3 requests on the front-end and while one request is in progress it executes another, so it returns several types of errors:
sqlalchemy.exc.DBAPIError: (_mysql_connector.MySQLInterfaceError) Commands out of sync; you cannot run this command now
sqlalchemy.orm.exc.DetachedInstanceError: The instance <OrderItem at 0x268967c8f50> is not linked to a session; the attribute update operation cannot proceed (History of this error at: https://sqlalche.me/e/20/bhk3)
Among other errors
Below is the way I set up the connection and then the way I call it in the request.
class__DBConnectionHandler:
def __init__(self) -> None:
self.__connection_string = "mysql+mysqlconnector://{user}:{password}@{host}/{database}".format(
)
self.__engine = None
self.session = None
def connect_to_db(self) -> None:
self.__engine = create_engine(self.__connection_string)
def create_tables(self):
Base.metadata.create_all(self.__engine)
def get_engine(self):
return self.__engine
def __enter__(self):
session_maker = sessionmaker(bind=self.__engine)
self.session = session_maker()
return to yourself
def __exit__(self, exc_type, exc_val, exc_tb):
self.session.close()
db_connection_handler=__DBConnectionHandler()
def get_all_order_items(self, order_id: int) -> OrderItem:
with db_connection_handler as database:
todos_order_items = (
database.session
.query(OrderItem, FoodItem)
.join(FoodItem)
.filter(OrderItem.orders_id == order_id)
.all()
)
return todos_order_items
It’s requested above as an example, but it calls out a bit of that at the same time.
I’ve already tried a few ways and I wasn’t successful, preferably I would like to just change the connection and solve the problem for the API calls, but if that wasn’t the case, that would be fine.
Felipe Vidal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.