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

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

解决方案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 fetchall returns rows as).

If you need to serialize more types (as in your case, you are getting back date rather than datetime instances, you will need to override Flask's json_encoder property with a subclass of JSONEncoder that knows how to handle your types:

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 Flask instance:

app.json_encoder = SpecializedJSONEncoder

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值