MySQL Connection not available when use SQLAlchemy(MySQL) and Flask

99封情书 提交于 2019-12-11 09:26:28

问题


I'm getting this error sometime (sometime is ok, sometime is wrong):

sqlalchemy.exc.OperationalError: (OperationalError) MySQL Connection not available.

while using session.query

I'm writing a simple server with Flask and SQLAlchemy (MySQL). My app.py like this:

Session = sessionmaker(bind=engine)
session = Session()

@app.route('/foo')
def foo():
    try:
        session.query(Foo).all()
    except Exception:
        session.rollback()

Update I also create new session in another file and call it in app.py

Session = sessionmaker(bind=engine)
session = Session()

def foo_helper(): #call in app.py
    session.query(Something).all()

Update 2 My engine:

engine = create_engine('path')

How can I avoid that error?

Thank you!


回答1:


Make sure the value of ‘pool_recycle option’ is less than your MYSQLs wait_timeout value when using SQLAlchemy ‘create_engine’ function.

engine = create_engine("mysql://username:password@localhost/myDatabase", pool_recycle=3600)

Try to use scoped_session to make your session:

from sqlalchemy.orm import scoped_session, sessionmaker
session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

and close/remove your session after retrieving your data.

session.query(Foo).all()
session.close()


来源:https://stackoverflow.com/questions/26891971/mysql-connection-not-available-when-use-sqlalchemymysql-and-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!