gpt4 book ai didi

python - SQLAlchemy 错误 MySQL 服务器已经消失

转载 作者:IT老高 更新时间:2023-10-29 00:11:40 25 4
gpt4 key购买 nike

错误 OperationalError: (OperationalError) (2006, 'MySQL server has gone away') 我在 Flask 上编写项目时已经收到此错误,但我不明白为什么会收到此错误.

我有这样的代码(是的,如果代码小且执行速度快,那么没有错误)\

db_engine = create_engine('mysql://root@127.0.0.1/mind?charset=utf8', pool_size=10, pool_recycle=7200)
Base.metadata.create_all(db_engine)

Session = sessionmaker(bind=db_engine, autoflush=True)
Session = scoped_session(Session)
session = Session()

# there many classes and functions

session.close()

这段代码给我返回错误'MySQL server has gone away',但是一段时间后,当我在我的脚本中使用暂停时返回它。

我从 openserver.ru 使用 Mysql(它是 web 服务器,例如 wamp)。

谢谢..

最佳答案

SQLAlchemy 现在有一篇关于如何使用 ping 对连接的新鲜度持悲观态度的精彩文章:

http://docs.sqlalchemy.org/en/latest/core/pooling.html#disconnect-handling-pessimistic

从那里开始,

from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy.pool import Pool

@event.listens_for(Pool, "checkout")
def ping_connection(dbapi_connection, connection_record, connection_proxy):
cursor = dbapi_connection.cursor()
try:
cursor.execute("SELECT 1")
except:
# optional - dispose the whole pool
# instead of invalidating one at a time
# connection_proxy._pool.dispose()

# raise DisconnectionError - pool will try
# connecting again up to three times before raising.
raise exc.DisconnectionError()
cursor.close()

并进行测试以确保上述工作正常:

from sqlalchemy import create_engine
e = create_engine("mysql://scott:tiger@localhost/test", echo_pool=True)
c1 = e.connect()
c2 = e.connect()
c3 = e.connect()
c1.close()
c2.close()
c3.close()

# pool size is now three.

print "Restart the server"
raw_input()

for i in xrange(10):
c = e.connect()
print c.execute("select 1").fetchall()
c.close()

关于python - SQLAlchemy 错误 MySQL 服务器已经消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16341911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com