2015-12-06 101 views
0

我有一個簡單的Flask web應用程序,它使用peewee來管理MySQL連接。不幸的是,它似乎錯過了我的代碼中的一些重要內容,因此,在使用該網站10-20分鐘後,我收到了一個pymysql.err.OperationalError: (2006, "MySQL server has gone away..錯誤。如果我重新啓動應用程序它再次正常工作,所以我假設我處理連接/連接錯誤。在Flask web應用程序中使用peewee維護MySQL連接

我有一些基本的查詢,我用來在我的用戶界面上顯示列表。由於我是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() 

回答

相關問題