问题描述
sqlalchemy.exc.OperationalError: (OperationalError)MySQL连接不可用。
使用 session.query
我正在用Flask和SQLAlchemy(MySQL)编写一个简单的服务器。我的 app.py
是这样的:
Session = sessionmaker(bind =引擎)
session = Session()
@ app.route('/ foo')
def foo():
try:
session。除了例外:
session.rollback()
以外的查询(Foo).all 我还在另一个文件中创建新的会话
,并在 app.py
Session = sessionmaker(bind =引擎)
session = Session()
def foo_helper():#call in app.py
session.query(Something).all()
更新2
我的引擎
:
engine = create_engine('path')
我可以避免这个错误吗?
谢谢!
Make确保'pool_recycle选项'的值小于你的MYSQL的wait_timeout值使用SQLAlchemy的'create_engine'函数。
$ b $ $ p $ engine = create_engine(mysql:// username:password @ localhost / myDatabase,pool_recycle = 3600)
尝试使用 scoped_session
从sqlalchemy.orm导入scoped_session,sessionmaker
session = scoped_session(sessionmaker(autocommit = False, autoflush = False,bind = engine))
在检索数据后关闭/删除会话。 / p>
session.query(Foo).all()
session.close()
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()
UpdateI 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 2My engine
:
engine = create_engine('path')
How can I avoid that error?
Thank you!
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()
这篇关于MySQL连接在使用SQLAlchemy(MySQL)和Flask时不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!