flask自带的jsonify直接可以返回json数据
非常简洁
当然熟悉http的还可以自己写一个方法
实现跨域等等
代码如下:
# coding=utf-8
from flask import Flask,jsonify
import json
app = Flask(__name__)
@app.route("/index")
def index():
data = {
"name": "zhangsan",
"age": 18
}
#json_str = json.dumps(data)
#return json_str,200,{"Content-Type":"application/json"}
#帮助转换为json字符串, 并且设置响应头Content-Type: application/json
return jsonify(data)
@app.route("/hello")
def hello():
return jsonify(name="wancheng",subject="python")
if __name__ == '__main__':
app.run(host="127.0.0.1",port=5000,debug=True)