使用 Flask 框架编写的一个简单的 Python POST和GET接口
安装 Flask
pip install Flask
使用python实现POST接口
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/test', methods=['POST']) def submit(): # 获取 JSON 请求体 data = request.get_json() # 从请求体中提取参数 name = data.get('name') uuid = data.get('uuid') # 打印参数 print(f"Name: {name}, UUID: {uuid}") # 检查参数是否存在 if not name or not uuid: response = { 'status': 'error', 'message': 'Missing name or uuid', 'data': None } return jsonify(response), 400 # 响应内容 response = { 'status': 'success', 'message': 'Data received', 'data': { 'name': name, 'uuid': uuid } } return jsonify(response), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=6101, threaded=True) # 在局域网内可访问
使用python实现GET接口
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/test2', methods=['GET']) def get_info(): # 从请求参数中获取 name 和 uuid name = request.args.get('name') uuid = request.args.get('uuid') # 检查参数是否存在 if not name or not uuid: response = { 'status': 'error', 'message': 'Missing name or uuid', 'data': None } return jsonify(response), 400 # 返回规范的响应 response = { 'status': 'success', 'message': 'Data received', 'data': { 'name': name, 'uuid': uuid } } return jsonify(response), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=6101, threaded=True) # 在局域网内可访问