1、flask 写接口
第一次写数据接口,采用 flask 框架,还挺简单。只需几行代码就能完成一个简单的接口,例如:
from flask import Flask,jsonify,request
app = Flask(__name__)
@app.route('/hello',methods=['GET'])
def hello():
name = 'world'
if 'name' in request.args:
name = request.args['name']
data={'data': 'hello ' + name}
return jsonify(data)
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.run(port=5000)
运行后,在浏览器里输入 http://127.0.0.1:5000/hello?name=flask,即可获取到json数据 {"data":"hello flask"}
2、跨域问题
然而,接口提供给web使用时,ajax调用会遇到跨域问题,需修改response,设置 Access-Control-Allow-Origin 来解决。修改后如下:
from flask import Flask,jsonify,request,make_response
app = Flask(__name__)
@app.route('/hello',methods=['GET'])
def hello():
name = 'world'
if 'name' in request.args:
name = request.args['name']
data= jsonify({'data': 'hello '+ name})
res = make_response(data)
res.headers['Access-Control-Allow-Origin'] = '*'
return res
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.run(port=5000)
网友评论