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

时间:2015-12-06 22:49:13

标签: python mysql flask peewee

我有一个简单的Flask Web应用程序,它使用peewee来管理MySQL连接。不幸的是,我似乎错过了我的代码中的重要内容,因此我在使用该网站10-20分钟后收到# 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() 错误。如果我重新启动应用程序它再次正常工作,所以我假设我处理连接/连接错误。

我有一些基本的查询,我用来在我的UI上显示列表。由于我是Python的新手,我的整个逻辑可能是错误的,所以如果有人能让我解释一下在我的情况下用peewee管理(连接 - 关闭连接)查询的正确方法,我会很高兴(简单的网站没有任何用户功能)。

您可以在下面的代码中看到我现在是怎么做的。在我连接之前一切正常,但在我连接到db之后,我只是在不处理连接的情况下调用查询。我假设我应该根据已调用的查询关闭连接,但找不到合适的方法。调用myDB.close()是不够的,或者我错误地使用它。

{{1}}

1 个答案:

答案 0 :(得分:4)

您需要根据请求/响应重新连接。 http://docs.peewee-orm.com/en/latest/peewee/database.html#adding-request-hooks

甚至还有关于Flask的部分。