1、demo1:登录接口
1.1 Flask代码
from flask import request, Flask, jsonify
# 创建1个实例
app = Flask(__name__)
# 解决接收中文报文乱码问题
app.config['JSON_AS_ASCII'] = False
# 登录接口
# 指定路由和请求方法。strict_slashes=False 对URL最后的/符合是否严格要求。False时,路径带不带/都可以。如果是True, 不能加/
@app.route('/api/login', methods=['POST'], strict_slashes=False)
def login():
# debug信息,打印请求方法
print(request.method)
# 获取请求数据,将数据变成字典
data = request.get_json()
# 打印请求的数据
print(data)
print(type(data))
# 定义用户名和密码变量,从data中取值
username = data['username']
pwd = data['password']
"""
测试场景(可以根据实际测试情况进行补充):
1、参数为空
2、用户名密码正确
3、用户密码错误
"""
if username == "" or pwd == "":
"""
Flask框架里,可以用jsonify返回json数据
使用jsonify时,返回的http response的Content-Type是application/json
这样做是符合HTTP协议规定的,这就是使用jsonify的原因之一
"""
return jsonify({
"code": "001",
"msg": "username or password can not be null"
})
elif username == "zz" and pwd == "123456":
return jsonify({
"address": {
"city": "beijing"
},
"httpstatus": 200,
"info": {
"age": 18,
"name": "zz"
},
"msg": "success",
"token": "2334nkdnknkadfnkndafkanfdkasnk"
})
else:
return jsonify({
"code": "001",
"msg": "username or password is not correct"
})
if __name__ == '__main__':
# debug=True 开启调试模式
# 非debug模式,如果运行的时候代码报错了,网页不会提示详细错误,只会报服务器内部错误
app.run(debug=True)
1.2 客户端请求
test_case.py
import requests
import pytest
# 账号和密码正确
def test_01():
data = {
"username": "cc",
"password": "123456"
}
url = "http://127.0.0.1:5000/api/login"
resp = requests.post(url=url, json=data)
print(resp)
print(resp.text)
# 账号密码都为空
def test_02():
data = {
"username": "",
"password": ""
}
url = "http://127.0.0.1:5000/api/login"
resp = requests.post(url=url, json=data)
print(resp)
print(resp.text)
# 账号或密码不正确
def test_03():
data = {
"username": "c",
"password": "123456"
}
url = "http://127.0.0.1:5000/api/login"
resp = requests.post(url=url, json=data)
print(resp)
print(resp.text)
if __name__ == '__main__':
pytest.main(['-s', 'test_case.py'])
1.3 执行效果
2、demo2:查询用户信息
2.1 Flask代码
# 查询个人用户信息接口
@app.route('/api/getuserinfo', methods=['GET'], strict_slashes=False)
def api_getUserInfo():
# 服务端希望token在headers中传过来,不是url
token = request.headers.get('token')
if token == "2334nkdnknkadfnkndafkanfdkasnk":
return jsonify({
'code': 200,
'data': [
{
"userid": 122222,
"username": "cc",
"nickname": "橙子",
"openid": "UWENSNNIFIIF3i43344",
"userbalance": 5678.02,
"userpoints": 43221
}
]
})
else:
return jsonify({
"code": 1000,
"msg": "user info is incorrect"
})
2.2 客户端请求
修改test_01如下
def test_01():
data = {
"username": "cc",
"password": "123456"
}
url = "http://127.0.0.1:5000/api/login"
resp = requests.post(url=url, json=data)
print(resp)
print(resp.text)
token = resp.json()['token']
# 基于获取的token来实现个人信息的查找
url = "http://127.0.0.1:5000/api/getuserinfo"
headers = {
"token": token
}
resp = requests.get(url=url, headers=headers)
print(resp)
print(resp.text)