Get 请求
开发一个只接受get方法的接口,接受参数为name和age,并返回相应内容。
**方法 1:****
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| from flask import Flask from flask import request from flask import redirect from flask import jsonify import json
app = Flask(__name__)
@app.route("/test_1.0", methods=["GET"]) def check(): return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False} if request.args is None: return_dict['return_code'] = '5004' return_dict['return_info'] = '请求参数为空' return json.dumps(return_dict, ensure_ascii=False) get_data = request.args.to_dict() name = get_data.get('name') age = get_data.get('age') return_dict['result'] = tt(name, age)
return json.dumps(return_dict, ensure_ascii=False)
def tt(name, age): result_str = "%s今年%s岁" % (name, age) return result_str
if __name__ == '__main__': app.run(host='0.0.0.0', port=80)
|
此种方式对应的request请求方式:
- 拼接请求链接, 直接请求:http://0.0.0.0/test_1.0?name=ccc&age=18
- request 请求中带有参数,如下图
方法 2:
1 2 3
| @app.route('/api/banWordSingle/<string:word>', methods=['GET']) def banWordSingleStart(word): return getWordStatus(word)
|
此方法 与 方法 1 中的拼接链接相似,但是不用输入关键字
请求链接:http://0.0.0.0/api/banWordSingle/输入词
Post 请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| from flask import Flask from flask import request from flask import redirect from flask import jsonify import json
app = Flask(__name__)
@app.route("/test_1.0", methods=["POST"]) def check(): return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False} if request.args is None: return_dict['return_code'] = '5004' return_dict['return_info'] = '请求参数为空' return json.dumps(return_dict, ensure_ascii=False) get_data = request.args.to_dict() name = get_data.get('name') age = get_data.get('age') return_dict['result'] = tt(name, age)
return json.dumps(return_dict, ensure_ascii=False)
def tt(name, age): result_str = "%s今年%s岁" % (name, age) return result_str
if __name__ == '__main__': app.run(host='0.0.0.0', port=8080)
|
请求方式: