网络编程
位置:首页>> 网络编程>> Python编程>> Python+flask实现restful接口的示例详解

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

作者:just-do-it-zzj  发布时间:2023-03-23 08:34:55 

标签:Python,flask,restful接口

1.第一个实例:HelloWorld

1.编写python代码

from flask import Flask
app=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,jsonify
import requests
tasks = []
@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,jsonify
import 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,jsonify

app=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接口的示例详解

来源:https://blog.csdn.net/henku449141932/article/details/128917288

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com