我有一个简单的 Flask 网络应用程序,它使用 peewee 来管理 MySQL 连接。不幸的是,我似乎从我的代码中遗漏了一些重要的东西,因此我在使用 10-20 分钟后收到 pymysql.err.OperationalError: (2006, "MySQL server has gone away..
错误站点。如果我重新启动该应用程序,它会再次正常工作,所以我假设我处理了错误的连接。
我有一些用于在我的 UI 上显示列表的基本查询。由于我是 Python 的新手,所以我的整个逻辑可能是错误的,所以如果有人能解释一下在我的案例中使用 peewee 管理(连接-关闭连接)查询的正确方法是什么,我会非常高兴(简单的网站没有任何用户函数)。
你可以在下面的代码中看到我现在是怎么做的。在我连接之前一切正常,但在我连接到数据库之后,我只是在不处理连接的情况下调用查询。我假设我应该根据已调用的查询关闭连接,但找不到正确的方法。调用 myDB.close() 是不够的,或者我用错了。
# this is how I connect to the MySQL
import peewee as pw
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
myDB = pw.MySQLDatabase("", host="", user="", passwd="")
class MySQLModel(pw.Model):
"""A base model that will use our MySQL database"""
class Meta:
database = myDB
class city(MySQLModel):
...
class building(MySQLModel):
...
myDB.connect()
# this is how I manage the homepage
cityList = []
cityList = city.select().order_by(city.objectId).limit(15)
buildings = []
buildings = building.select().order_by(building.buildingName).limit(180)
def getSearchResult (content_from_url):
searchResultList = []
searchResultList = city.select().where(city.objTitle.contains(content_from_url))
return searchResultList
@app.route('/', methods=['GET', 'POST'])
def main_page():
search = request.args.get('search')
if search:
return render_template("results.html", search = getSearchResult(search), str = search)
else:
return render_template("home.html", name=cityList, buildList=buildings)
# and this is how the subpage
relatedCityList = []
slugObj = []
buildings2 = []
buildings2 = building.select().order_by(building.buildingName).limit(180)
def getLink (title_for_link):
slugObj = city.get(city.urlSlug == title_for_link)
return slugObj
def displayRelatedCity (city_to_filter):
resultCity = city.get(city.urlSlug == city_to_filter)
relatedCityList = city.select().where(city.objTitle == resultCity.objTitle).limit(20)
return relatedCityList
@app.route('/city-list/<content>', methods=['GET', 'POST'])
def city_page(content):
linkText = getLink(content)
return render_template("details.html", relatedCity = displayRelatedCity(content), buildingName = linkText.buildingName, buildz = buildings2)
myDB.close()
最佳答案
您需要根据请求/响应重新连接。 http://docs.peewee-orm.com/en/latest/peewee/database.html#adding-request-hooks
甚至还有一个关于 Flask 的部分。
关于python - 在 Flask 网络应用程序中维护 MySQL 与 peewee 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34123823/