Python 如何从 Flask 应用程序中的 MySQL 查询返回数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21709992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:27:38  来源:igfitidea点击:

How to return data from a MySQL query in a Flask app?

pythonmysqlflask

提问by Hugo

I have the following code:

我有以下代码:

import flask as fk
import MySQLdb
import JSONEncoder


class SpecializedJSONEncoder(JSONEncoder):
    def default(o):
        if isinstance(o, date):
            return date.strftime("%Y-%m-%d")
        else:
            super(SpecializedJSONEncoder, self).default(o)

app = fk.Flask(__name__)
app.json_encoder = SpecializedJSONEncoder
app.debug = True

@app.route("/")
def home():
   return "Hello world"

@app.route("/temp")
def temp():
    db = MySQLdb.connect("localhost", "root", "","test")
    cur = db.cursor()
    query = "SELECT DATE(DTM), POM, ROUND(MIN(TMP),1) FROM dados_meteo WHERE POM = %s AND      DATE(DTM) >= %s AND DATE(DTM) <= %s"
    param = ("Faro", "2013-12-01", "2013-12-05")
    cur.execute(query, param)
    data = cur.fetchall()

    return data.json_encoder()

 if __name__ == "__main__":
    app.run()

The error returned is: ImportError: No module named JSONEncoder

返回的错误是:ImportError: No module named JSONEncoder

采纳答案by Sean Vieira

Use Flask's built-in jsonifyfunction, as it is already extended to work with dates:

使用 Flask 的内置jsonify函数,因为它已经扩展到可以处理日期

from Flask import jsonify

@app.route('/temp')
def temp():
    # Load database results
    # and then ...
    return jsonify(data=cur.fetchall())

The data will be returned as an object with a single key (data) containing an array of rows (which will either be represented as arrays or objects depending on what fetchallreturns rows as).

数据将作为一个对象返回,data其中包含一个包含行数组的单个键 ( )(根据fetchall返回行的内容,该对象将表示为数组或对象)。

If you need to serialize more types (as in your case, you are getting back daterather than datetimeinstances, you will need to override Flask's json_encoderproperty with a subclass of JSONEncoderthat knows how to handle your types:

如果您需要序列化更多类型(在您的情况下,您将返回date而不是datetime实例,您将需要json_encoder使用JSONEncoder知道如何处理您的类型的子类覆盖 Flask 的属性:

class SpecializedJSONEncoder(JSONEncoder):
    def default(o):
        if isinstance(o, date):
            return date.strftime("%Y-%m-%d")
        else:
            super(SpecializedJSONEncoder, self).default(o)

And then you can set it on your Flaskinstance:

然后你可以在你的Flask实例上设置它:

app.json_encoder = SpecializedJSONEncoder

You will now be able to handle dates as well as datetimes.

您现在将能够处理dates 和datetimes。