Flask : GET-POST
from flask import Flask, request, jsonify from flask_restful import Api, Resource, reqparse app = Flask(__name__) api = Api(app) #### --GET请求参数-- 传递参数到 GET 请求中 #### # 1. GET 传递查询字符串参数 # URL 进行 GET 请求: http://localhost:5000/users?name=John&age=30 @app.route('/users') def get_users(): name = request.args.get('name') age = request.args.get('age') return f"Hello, {name}! You are {age} years old." # 2. GET 传递路径参数 # URL 进行 GET 请求: http://localhost:5000/users/John @app.route('/users/<name>') def get_user1(name): return f"Hello, {name}!" # 3. GET 传递多个路径参数 # URL 进行 GET 请求:http://localhost:5000/users/John/30 @app.route('/users/<name>/<age>') def get_user2(name, age): return f"Hello, {name}! You are {age} years old." # 4. GET 请求参数验证 # URL 进行 GET 请求:http://localhost:5000/user?name=John&age=30 parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=True, location="args", help='Name is required.') parser.add_argument('age', type=int, required=True, location="args", help='Age is required.') class UserResource(Resource): def get(self): args = parser.parse_args() name = args['name'] age = args['age'] # Step 1. 业务逻辑处理 todo if name != "姜山": name = "姜山" age = 18 # Step 2. 业务逻辑处理封装(Json格式) todo processed_data = {"code": 200, 'message': f"Hello, {name}! You are {age} years old."} return jsonify(processed_data)# 将结果转换为JSON格式返回 api.add_resource(UserResource, '/user') #### --POST提交表单-- #### @app.route('/flask/data', methods=['POST']) def process_post_request(): data = request.get_json() # 获取POST请求中的JSON数据 # Step 1. 业务逻辑处理 todo # Step 2. 业务逻辑处理封装(Json格式) todo processed_data = {"code": 200, 'result': f"Processed Data: {data}"} return jsonify(processed_data)# 将结果转换为JSON格式返回 if __name__ == "__main__": # 解决jsonify中文乱码问题 app.config['JSON_AS_ASCII'] = False # Do not use it in a production deployment. Use a production WSGI server instead. app.run(host="0.0.0.0", port=5000, debug=True)
个人学习记录