Flask Tutorial (27) JSON Data Interaction

surroundings

  • windows 10 64bit
  • anaconda3 with python 3.8.11
  • flask 2.2.2

foreword

json is the most common method of data transmission between modules, and flask can also easily receive and return data in json format.

Practical

To see the complete server code, use the flask .request method in get_json here

 from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/', methods=['POST']) def post(): # 获取请求的json数据req_json = request.get_json() print(req_json) # 对接收到的数据进行简单处理if req_json["operatorID"] != "0001": return jsonify({"error": "error."}) dict_ret = {} dict_ret["responseType"] = 2 dict_ret["status"] = 1000 dict_ret["num"] = 1 dict_ret["MD5"] = "4F3D2A1E" return jsonify(dict_ret) if __name__ == '__main__': # 启动服务app.run(host='0.0.0.0', port=80, debug=True)

Then, start the service. We use the postman tool to model client requests

postman sends the request, you can get a response, and the response data is also a json

If the operatorID in the request json is not 0001, the server will return error

If you need programming to implement the request, you can use the requests library

 import requests r_json = { "name": "xgx", "operatorID":"0001", "requestType":1, "num":1 } r_headers = {"Content-type": "application/json"} r = requests.post('http://127.0.0.1', json=r_json, headers=r_headers) print(r.status_code) print(r.json())

Source code download

https://github.com/xugaoxiang/FlaskTutorial

Flask Series Tutorials

For more Flask tutorials, please move

https://xugaoxiang.com/category/python/flask/

This article is transferred from https://xugaoxiang.com/2022/12/05/flask-27-json/
This site is only for collection, and the copyright belongs to the original author.