使用Python Flask获取curl传来的JSON数据
一、POST传送参数
使用curl命令传送字典:
curl http://192.168.1.10:5000/upload -X POST -d '{"hello": "world"}' --header "Content-Type: application /json"
使用Python Flask的request.json获取字典数据:
from flask import Flask, request app = Flask(__name__) @app.route("/upload", methods=["POST"]) def save_file(): print("start...") # 获取json数据 print(type(request.json)) print(request.json['hello']) print("end...") return "已接收保存\n" if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=True)
二、URL中传递参数
也可以使用在URL中携带参数:
curl http://192.168.68.10:5000/upload?info=1233232 -X POST --header "Content-Type: application/json"
from flask import Flask, request app = Flask(__name__) @app.route("/upload", methods=["POST"]) def save_file(): print("start...") # 从URL里获取参数 print(request.args.__str__()) print(request.args.get('info')) print("end...") return "已接收保存\n" if __name__ == '__main__': app.run(host="0.0.0.0", port=5000, debug=True)
参考:
1. https://www.letianbiji.com/python-flask/py-flask-json.html