示例一:
实现动态路由,代码如下
# coding:utf-8
from flask import Flask
from flask import jsonify
# 创建对象
app = Flask(__name__)
users_list = {"1001":["123","张三",19],
"1002":["234","李四",22],
"1003":["345","王二小",8]}
# 编写路由,构建url与函数的映射关系(将函数与url绑定)
@app.route("/users",methods=["GET"])
def users():
return jsonify({"code":10000,"message":"success","data":users_list})
# 动态路由,语法:<类型:变量名>
@app.route("/users/<string:account>",methods=["GET"])
def get_user(account):
if account in users_list:
info = users_list[account]
return jsonify({"code":10000,"message":"success","data":{"name":info[1],"age":info[-1]}})
else:
return jsonify({"code":10001,"message":"success","data":"账户不存在"})
if __name__ == '__main__':
# 解决jsonify中文乱码问题
app.config['JSON_AS_ASCII'] = False
# 以调试模式启动,host=0.0.0.0 ,则可以使用127.0.0.1、localhost以及本机ip来访问
app.run(host="0.0.0.0",port=8899,debug=True)
查看users接口效果
查看不存在的账户信息
查看单个账户信息
示例二:
实现get请求传参
代码如下
# coding:utf-8
from flask import Flask
from flask import jsonify
from flask import request
# 创建对象
app = Flask(__name__)
users_list = {"1001":["123","张三",19],
"1002":["234","李四",22],
"1003":["345","王二小",8]}
# 编写路由,构建url与函数的映射关系(将函数与url绑定)
@app.route("/users",methods=["GET"])
def users():
return jsonify({"code":10000,"message":"success","data":users_list})
@app.route("/users/account",methods=["GET"])
def get_user():
# 获取请求中的参数account的值
account = request.args.get("account")
if account:
if account in users_list:
info = users_list[account]
return jsonify({"code":10000,"message":"success","data":{"name":info[1],"age":info[-1]}})
else:
return jsonify({"code":10001,"message":"success","data":"账户不存在"})
else:
return jsonify({"code":10001,"message":"success","data":"账户为空"})
if __name__ == '__main__':
# 解决jsonify中文乱码问题
app.config['JSON_AS_ASCII'] = False
# 以调试模式启动,host=0.0.0.0 ,则可以使用127.0.0.1、localhost以及本机ip来访问
app.run(host="0.0.0.0",port=8899,debug=True)
参数为空,效果如下
传递正常参数,效果如下