您当前的位置: 首页 >  彭世瑜 flask

Flask的钩子函数与peewee.InterfaceError: (0, '')

彭世瑜 发布时间:2018-12-28 22:56:07 ,浏览量:2

问题

使用flask搭了一个服务,用到了peewee模块,运行时间长了就报错

peewee.InterfaceError: (0, '')

百度上一搜,发现有自己的文章

peewee: OperationalError: (2006, ‘MySQL server has gone away’)

那个时候,处理的是peewee2版本的问题,如今又在处理peewee3的问题,真是问题多多

解决

查看peewee的issue,看到一个回到,给出两个方案 1、使用flask-peewee 模块 2、使用flask的钩子函数

尝试使用方案2: request来的时候打开数据库连接,response返回的时候关闭数据库连接

根据文档给出的代码

from flask import Flask
from peewee import *

database = SqliteDatabase('my_app.db')
app = Flask(__name__)

# This hook ensures that a connection is opened to handle any queries
# generated by the request.
@app.before_request
def _db_connect():
    database.connect()

# This hook ensures that the connection is closed when we've finished
# processing the request.
@app.teardown_request
def _db_close(exc):
    if not database.is_closed():
        database.close()

参考:

  1. https://github.com/coleifer/peewee/issues/1546
  2. http://docs.peewee-orm.com/en/latest/peewee/database.html#flask
  3. http://docs.peewee-orm.com/en/latest/peewee/database.html#error-2006-mysql-server-has-gone-away
关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 2浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0537s