问题:后端接口已提供,前端需要依赖后端接口返回的数据进行前端页面的开发,如何配合前端?
mock接口
flask自定义接口实现查询接口:查询全部、部分查询
具体看下面的代码:
#导入包
from flask import Flask,jsonify
#定义内容属性
app = Flask(__name__)
#处理中文乱码问题
app.config["JSON_AS_ASCII"]=False
#接口数据,接口文档(已知) 多个参数
user_data=[
{"id":1,"username":"王建华","password":"123456","phone":"xxx"},
{"id":2,"username":"王建华2","password":"123456","phone":"xxx"},
{"id":3,"username":"王建华3","password":"123456","phone":"xxx"},
{"id":4,"username":"王建华4","password":"123456","phone":"xxx"},
{"id":5,"username":"王建华5","password":"123456","phone":"xxx"}
]
#定义接口
@app.route("/users",methods=["GET"])
def get_all_userInfo():
'''获取全部用户信息'''
#接口返回数据 序列化处理 json.dumps(); json.loads()-字典
return jsonify({"status":1,"data":user_data,"msg":"查询成功"})
@app.route("/user/<int:user_id>",methods=["GET"])
def get_a_userInfo(user_id):
'''获取某一个用户的信息'''
if user_id>0 and user_id<=len(user_data):
return jsonify({"status":1,"data":user_data[user_id-1],"msg":"查询成功"})
return jsonify({"status":0,"msg":"查无记录"})
@app.route("/login",methods=["POST"])
def user_login():
'''用户登录'''
#获取用户信息
uname= request.json.get("username")
pwd=request.json.get("password")
if uname and pwd:
if uname == "王建华" and pwd =="123456":
return jsonify({"code":2000,"msg":"登录成功","sid":"fwewsewrfdss-oooaww"})
return jsonify({"code":4001,"msg":"用户名或密码错误!"})
else:
return jsonify({"code":4002,"msg":"用户名或密码不能为空!"})
if __name__ == '__main__':
app.run(debug=True) #执行时可以看到详细的执行情况
在浏览器中访问接口:
在脚本中访问:
import requests def test_getUsers(): url="http://127.0.0.1:5000/users" res=requests.get(url) print("接口返回数据:{}".format(res.text)) def test_getUsers1(): headers={""} url="http://127.0.0.1:5000/user/1" res=requests.get(url) print("接口返回数据:{}".format(res.text)) if __name__ == '__main__': test_getUsers() # test_getUsers1()