Forums

(2013, 'Lost connection to MySQL server during query') and 500 internal error

I'm developing an api app using Flask, SQLAlchemy and mysql and every few minutes my server returns 500 internal error and then continues to work normally. I tried to set wait_timeout and loop_recycle, but it didn't help

Error log:

sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2013, 'Lost connection to MySQL server during query')
[SQL: SELECT card.id AS card_id, card.img AS card_img, card.date AS card_date, card.category_id AS card_category_id, card.vk_url AS card_vk_url 
FROM card]

Below is an example of how I connect to the database, there may be a problem here:

Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)

@contextmanager
def get_session():

    try:
        yield session
    except:
        session.rollback()
        raise
    finally:
        session.commit()

session = DBSession()


def delete_category(name):
    with get_session() as session:
        category = select_category(name)
        if category:
            session.delete(category)
            # session.commit()
            return True
        else:
            print("Не удалось удалить категорию")
            return False

[formatted by admin]

Hi, could you show us the code for engine as well?

:::python

from sqlalchemy import *   
from config import db_user, db_password, db_host
db_name = 'pozdravko$default'

url = "mysql://{0}:{1}@{2}".format(db_user, db_password, db_host)
db = url + f"/{db_name}?charset=utf8mb4"

engine = create_engine(db, pool_timeout=20, pool_recycle=3600)

Hi, thanks. Try setting pool_recycle kwarg to something less than 300, like 280. BTW we've got a (short) help page for that issue: https://help.pythonanywhere.com/pages/UsingSQLAlchemywithMySQL/

Thank you, I hope this helps me