Tornado + sqlalchemy在SAE上出现2006, 'MySQL server has gone away' 错误
设计了一个定时任务,执行时间大概在30秒,在邮件收取的环节耗时较长,从日志里看大概每半小时就会出现一次
MySQL server has gone away
的报错。
已经按照谷歌到的建议,把sqlalchemy的pool_recycle参数重设了。
engine = create_engine(db_config, pool_recycle=5, pool_size=20)
附上我的代码:
class ApplyReplyHandler(BaseHandler):
def get(self):
try:
reply = self.session.query(func.max(Reply.mail_id).label('max_mail_id')).one()
offset = reply.max_mail_id if reply.max_mail_id else 0
for mail_id, mail_addr, mail_subject, mail_body in receive_mail(offset):
m = search(r'\[##(.+)##\]', mail_subject)
if not m:
continue
apply_secret = m.group(1)
related_apply = self.session.query(Apply).filter(Apply.secret_key == apply_secret).filter(
Apply.mail_addr == mail_addr).first()
if not related_apply:
continue
reply = Reply(apply_id=related_apply.id, mail_id=mail_id, mail_subject=mail_subject,
mail_body=mail_body)
self.session.add(reply)
related_apply.status = 4
self.session.commit()
self.write('success')
except Exception, e:
logging.exception(e)
self.write('failed')
BaseHandler是这样初始化和关闭MySQL连接的:
class BaseHandler(tornado.web.RequestHandler):
def initialize(self):
self.session = DB_Session()
def on_finish(self):
self.session.close()
python sqlalchemy sina-app-engine tornado mysql
kawenwu
11 years ago