使用Python Flask快速构建一个api server
使用 flask 快速构建一个api server
代码如下:
from flask import Flask, jsonify, request app = Flask(__name__) # 定义一个路由,当访问根路径时返回欢迎信息 @app.route('/') def home(): return 'Hello, this is a simple API!' # 定义一个路由,接受GET请求并返回JSON响应 @app.route('/api/data', methods=['GET']) def get_data(): data = {'key': 'value'} return jsonify(data) # 定义一个路由,接受POST请求并返回请求体中的数据 @app.route('/api/data', methods=['POST']) def post_data(): data = request.json return jsonify(data) if __name__ == '__main__': app.run(debug=True)
返回
* Serving Flask app 'flash' * Debug mode: on WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000 Press CTRL+C to quit * Restarting with watchdog (windowsapi) * Debugger is active! * Debugger PIN: 585-354-472 127.0.0.1 - - [09/Jul/2024 18:59:34] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [09/Jul/2024 18:59:35] "GET /favicon.ico HTTP/1.1" 404 - 127.0.0.1 - - [09/Jul/2024 18:59:50] "GET /api/data HTTP/1.1" 200 -
本文来自博客园,作者:方倍工作室,转载请注明原文链接:https://www.cnblogs.com/txw1958/p/18292587/python-flask