python flask 提供web的get/post开发

转载请注明出处:

  使用python flask框架编写web api中的get与post接口,代码编写与调试示例如下:

from flask import Flask, request, jsonify  app = Flask(__name__)  @app.route('/api/get', methods=['GET']) def handle_get_request():     try:         # 解析URL参数         param1 = request.args.get('param1')         param2 = request.args.get('param2')          # 在这里处理GET请求的逻辑         # ...          # 返回响应体为JSON数据         response = {'message': 'Success', 'data': {'param1': param1, 'param2': param2}}         return jsonify(response)     except Exception as e:         # 异常捕捉并返回错误信息         error_response = {'message': str(e)}         return jsonify(error_response), 500  @app.route('/api/post', methods=['POST']) def handle_post_request():     try:         # 解析JSON请求体         json_data = request.get_json()          # 在这里处理POST请求的逻辑         # ...          # 返回响应体为JSON数据         response = {'message': 'Success', 'data': json_data}         return jsonify(response)     except Exception as e:         # 异常捕捉并返回错误信息         error_response = {'message': str(e)}         return jsonify(error_response), 500  if __name__ == '__main__':     app.run(host='0.0.0.0', port=5000)

  启动这段代码,并调试:

  python flask 提供web的get/post开发

  使用curl命令调试接口:

python flask 提供web的get/post开发

  curl的命令如下:

  使用curl发送GET请求的命令示例:

curl 'http://localhost:15000/api/get?param1=value1&param2=value2'

  使用curl发送POST请求的命令示例:

curl -X POST -H 'Content-Type: application/json' -d '{"key1": "value1", "key2": "value2"}' http://localhost:15000/api/post

  后台运行python:

  运行以下命令来启动Flask服务,并将输出重定向到一个日志文件(例如flask.log)中:

nohup python your_flask_app.py > flask.log 2>&1 &

 

发表评论

评论已关闭。

相关文章