在 Flask 网络应用程序中维护与 peewee 的 MySQL 连接

Maintaining MySQL connection with peewee in a Flask web app

我有一个简单的 Flask 网络应用程序,它使用 peewee 来管理 MySQL 连接。不幸的是,我的代码似乎遗漏了一些重要的东西,因此我在使用该网站 10-20 分钟后收到 pymysql.err.OperationalError: (2006, "MySQL server has gone away.. 错误。如果我重新启动应用程序,它会再次正常工作,所以我假设我处理了 connection/connections 错误。

我有一些基本查询用于在 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()

您需要在 request/response 重新连接。 http://docs.peewee-orm.com/en/latest/peewee/database.html#adding-request-hooks

甚至还有一个关于 Flask 的部分。