suchen

Heim  >  Fragen und Antworten  >  Hauptteil

python - 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()
阿神阿神2768 Tage vor508

Antworte allen(2)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:58:37

    是两次访问mysql的间隔时间会比较长吗,如果是这样的话,我的建议是每次使用db连接时候先session.close()一下,这样连接总是重新建立的

    Antwort
    0
  • ringa_lee

    ringa_lee2017-04-17 13:58:37

    貌似pool_recycle设置也不起作用,楼主后来怎么解决的

    Antwort
    0
  • StornierenAntwort