>1.第一个实例:HelloWorld

2.Post 方法

3.Get 方法

4.通过变量设置动态url

1.第一个实例:HelloWorld

1.编写python代码

from flask import Flaskapp=Flask(__name__)@app.route('/HelloWorld')def hello_world():    return "Hello World!"if __name__ == "__main__":    app.run(host='127.0.0.1',port=8085,debug=True)

2.运行代码

Python+flask实现restful接口的示例详解

3.在浏览器输入访问地址

http://127.0.0.1:8085/HelloWorld

Python+flask实现restful接口的示例详解

2.Post 方法

1.编写接口

from flask import Flask,abort,request,jsonifyimport requeststasks = []@app.route('/add_user', methods=['POST'])def add_user():    if not request.json  or 'id' not in request.json or 'name' not in request.json:        abort(400)    task = {        'id': request.json['id'],        'name': request.json['name']    }    tasks.append(task)    return jsonify({'result': 'success'})if __name__ == "__main__":    app.run(host='127.0.0.1',port=8085,debug=True)

2.运行接口

Python+flask实现restful接口的示例详解

3 使用postman测试

1)设置Headers参数

Python+flask实现restful接口的示例详解

2)设置body参数后点击“Send”

Python+flask实现restful接口的示例详解

3)返回值

Python+flask实现restful接口的示例详解

3.Get 方法

1.编写代码

from flask import Flask,abort,request,jsonifyimport requests@app.route('/get_user', methods=['GET'])def get_user():    if not request.args or 'id' not in request.args:        return jsonify(tasks)    else:        task_id = request.args['id']        task = filter(lambda t: t['id'] == int(task_id), tasks)        return jsonify(task) if task else jsonify({'result': 'not found'})if __name__ == "__main__":    app.run(host='127.0.0.1',port=8085,debug=True)

2.运行接口

Python+flask实现restful接口的示例详解

3.使用postman测

Python+flask实现restful接口的示例详解

4.通过变量设置动态url

通过在route中添加变量<var_name>,同时把变量作为函数参数,可以实现动态url

1.编写代码

from flask import Flask,abort,request,jsonifyapp=Flask(__name__)@app.route('/getUser/<userName>')def getUser(userName):    return "Hello:{}!".format(userName)if __name__ == "__main__":    app.run(host='127.0.0.1',port=8085)

2.运行接口

Python+flask实现restful接口的示例详解

3.在浏览器输入访问地址

http://127.0.0.1:8085/getUser/zhangsan

Python+flask实现restful接口的示例详解

http://127.0.0.1:8085/getUser/lisi

Python+flask实现restful接口的示例详解

以上就是Python+flask实现restful接口的示例详解的详细内容,更多关于Python flask实现restful接口的资料请关注其它相关文章!

原文地址:https://blog.csdn.net/henku449141932/article/details/128917288

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
猜你喜欢
  • 2021-11-29
  • 2022-12-23
  • 2023-03-16
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案