# 原文:https://blog.csdn.net/mouday/article/details/85332510
Flask的鈎子函數與peewee.InterfaceError: (0, '')
2018年12月28日 22:56:07 彭世瑜 閱讀數:70更多
個人分類: flask
版權聲明:本文為博主原創文章,歡迎轉載,請注明出處 https://blog.csdn.net/mouday/article/details/85332510
問題
使用flask搭了一個服務,用到了peewee模塊,運行時間長了就報錯
peewee.InterfaceError: (0, '')
1
百度上一搜,發現有自己的文章
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()
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()
---------------------
作者:彭世瑜
來源:CSDN
原文:https://blog.csdn.net/mouday/article/details/85332510
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
參考:
https://github.com/coleifer/peewee/issues/1546
http://docs.peewee-orm.com/en/latest/peewee/database.html#flask
http://docs.peewee-orm.com/en/latest/peewee/database.html#error-2006-mysql-server-has-gone-away