flask的post,get请求及获取不同格式的参数
1 获取不同格式参数
1.0 获取json参数
- Demo
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/jsonargs/<string:args_1>', methods=['POST']) def json_args(args_1): args_2 = request.json.get("args_2") args_3 = request.json['args_3'] return jsonify({"args_1":args_1, "args_2":args_2, "args_3":args_3}) if __name__ == "__main__": app.run(host='0.0.0.0', port=8080, debug=True)
- request
1.2 获取form参数
- Demo
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/formargs/<int:args_1>', methods=['POST']) def form_args(args_1): args_2 = request.form.get('args_2') args_3 = request.form['args_3'] return jsonify({"args_1":args_1, "args_2":args_2, "args_3":args_3}) if __name__ == "__main__": app.run(host='0.0.0.0', port=8080, debug=True)
- request
1.3 get获取地址栏参数
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/getargs', methods=['GET', 'POST']) def get_args(): args_1 = request.args.get("args_1") args_2 = request.args.get("args_2") args_3 = request.args.get("args_3") return jsonify({"args_1":args_1, "args_2":args_2, "args_3":args_3}) if __name__ == "__main__": app.run(host='0.0.0.0', port=8080, debug=True)
Request
1.4 获取file文件
from flask import Flask, request, jsonify import os basedir = os.path.abspath(os.path.dirname(__name__)) app = Flask(__name__) @app.route('/imageprocess', methods=['GET', 'POST']) def image_preprocess(): # get upload image and save image = request.files['image'] path = basedir + "/source_images/" file_path = path + image.filename image.save(file_path) if __name__ == "__main__": app.run(host='0.0.0.0', port=8080, debug=True)
1.5 获取任何格式
from flask import Flask, request app = Flask(__name__) def upload_data(): data = request.values.get("input") return jsonify({"data type":"successfully upload!"}) if __name__ == "__main__": app.run(host="0.0.0.0", port=8090, debug=True)
2 文件格式解析
from flask import Flask, jsonify, request,abort import os app = Flask(__name__) def path_get(): path = os.path.abspath(os.path.dirname(__name__)) return path @app.route('/connect', methods=["GET"]) def connect(): return jsonify({"connect state":"successfully connect!"}) @app.route('/upload_data', methods=["GET", "POST"]) def upload_data(): # 判断form文件是否为空及是否是form文件 if request.form and 'input' in request.form: upload_data = request.form['input'] form_type = request.form print("form type: {}".format(form_type)) # return jsonify({"input data":upload_data}) return jsonify({"form data type":form_type}) # 判断json文件是否为空及是否是json文件 elif request.json and 'input' in request.json: upload_data = request.json['input'] # return jsonify({"input data":upload_data}) # return jsonify({"input test":"success"}) json_type = request.json print("json type: {}".format(json_type)) return jsonify({"form data type":json_type}) # 判断files文件是否为空及是否是files文件 elif 'input' in request.files: file = request.files["input"] path = path_get() + "/images/test.png" # file.save(path) files_type = request.files print("files type: {}".format(files_type)) return jsonify({"path":path}) # return jsonify({"form data type":files_type}) else: abort(400) if __name__ == "__main__": app.run(host='0.0.0.0', port=8098, debug=True)
Result
# form数据 form type: ImmutableMultiDict([('input', 'dancer')]) { "form data type": { "input": "dancer" } } ======================= # json数据 json type: {'input': 'jumper'} { "form data type": { "input": "jumper" } } ======================= # files文件 files type: ImmutableMultiDict([('input', <FileStorage: '1.jpeg' ('image/jpeg')>)])
Analysis
(1) form数据是可遍历的字典,可使用字典属性;
(2) json数据为字典,可使用字典属性;
(3) files数据为可遍历的字典,可使用字典属性,通过key判断是否存在该key,如input这个键;
(4) 当使用数据中的一种格式时,其他的数据为None,不可遍历,因此直接使用if判断是否为该类型的数据,会抛出错误TypeError: argument of type 'NoneType' is not iterable,所以通过先判断数据是否为空,然后判断是否为指定格式,解除错误;
3 获取checkbox数据
3.1 获取一个checkbox数据
- html
<p><input type="checkbox" name="checkbox_name" value="选择框">选择框</p>
- flask
data = request.values.get("checkbox_name")
3.2 获取多个checkbox数据
- html
<p><input type="checkbox" name="checkbox_names" value="选择1">选择1</p> <p><input type="checkbox" name="checkbox_names" value="选择1">选择2</p> <p><input type="checkbox" name="checkbox_names" value="选择1">选择3</p>
- flask
datas = request.values.getlist("checkbox_names")
3.3 分级选择
参考:https://www.cnblogs.com/kaituorensheng/p/4529113.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script> function allSelect(check_v, checkname) { var v_item = document.getElementsByName(check_v); var items = document.getElementsByName(checkname); for (var i = 0; i < items.length; ++i) { if (v_item[0].checked) { items[i].checked = true; } else { items[i].checked = false; } } } function singleSelect2parent(check_v, checkname) { var v_item = document.getElementsByName(check_v); var items = document.getElementsByName(checkname); var childStatus = true; for (var i = 0; i < items.length; ++i) { childStatus = (childStatus && items[i].checked); } if (childStatus) { v_item[0].checked = true; } else { v_item[0].checked = false; } } </script> </head> <body> <p> <input type="checkbox" checked name="checkbox_v1" value="version1" onclick="allSelect('checkbox_v1', 'checkbox1')">默认全选</p> <ul> <p> <input type="checkbox" checked name="checkbox1" value="layer1" onclick="singleSelect2parent('checkbox_v1', 'checkbox1')">tiger_roads</p> <p> <input type="checkbox" checked name="checkbox1" value="layer2" onclick="singleSelect2parent('checkbox_v1', 'checkbox1')">poly_landmarks</p> <p> <input type="checkbox" checked name="checkbox1" value="layer3" onclick="singleSelect2parent('checkbox_v1', 'checkbox1')">poi</p> </ul> <p> <input type="checkbox" name="checkbox_v2" value="version2" onclick="allSelect('checkbox_v2', 'checkbox2')">默认全不选</p> <ul> <p> <input type="checkbox" name="checkbox2" value="layer1" onclick="singleSelect2parent('checkbox_v2', 'checkbox2')" >tiger_roads</p> <p> <input type="checkbox" name="checkbox2" value="layer2" onclick="singleSelect2parent('checkbox_v2', 'checkbox2')">poly_landmarks</p> <p> <input type="checkbox" name="checkbox2" value="layer3" onclick="singleSelect2parent('checkbox_v2', 'checkbox2')">poi</p> </ul> </body> </html>
4 总结
(1) 数据获取使用request请求,常用数据格式有json,form,file及地址栏的get请求数据;
(2) form及json数据请求方式均有两种,如request.json.get(),request.json[];
(3) 获取文件数据,可通过filename属性获取文件名,save属性进行保存;
(4) 地址栏可直接写入数据,需在route的方法内使用格式为:<type:args>如<int:id>,<string:name>等;
(5) 通过判断输入数据的格式,提供不同类型的输入;
[参考文献]
[1]https://www.jianshu.com/p/ecd97b1c21c1
[2]https://blog.csdn.net/p571912102/article/details/80526634
[3]https://www.cnblogs.com/kaituorensheng/p/4529113.html
[4]https://blog.csdn.net/kuangshp128/article/details/68926902