問題
使用
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/15462.
http://docs.peewee-orm.com/en/latest/peewee/database.html#flask3.
http://docs.peewee-orm.com/en/latest/peewee/database.html#error-2006-mysql-server-has-gone-away