发布时间:2023-08-23 10:00
目录
服务端代码:
用postman测试三个api:
1.登录api:
2.检查登录状态api:
3.退出登录api:
from flask import Flask,request,jsonify,session
app = Flask(__name__)
app.secret_key = \'TPmi4aLWRbyVq8zu9v82dWYW1\'
# 登录
@app.route(\"/login\",methods=[\"POST\"])
def login():
\"\"\"
账号:admin
密码:123
:return:
\"\"\"
data = request.get_json() # 接受前段发送的数据(账号和密码)
username = data.get(\"username\") # 提取username对应的值
password = data.get(\"password\")
# 参数完整性的校验
if not all([username,password]):
return jsonify(re_code=400,msg=\"参数不完整\")
# 检验账号和密码是否正确
if username == \"admin\" and password == 123:
# 验证通过,保存登录状态在session中
session[\"username\"] = username
return jsonify(msg=\"登录成功\")
else:
return jsonify(msg=\"账号或密码错误\")
# 检查登录状态
@app.route(\"/session\", methods=[\"GET\"])
def check_session():
username = session.get(\"username\")
if username is not None:
return jsonify(username=username)
else:
return jsonify(msg=\"未登录\")
# 登出
@app.route(\"/logout\",methods=[\"DELETE\"])
def logout():
session.pop(\"username\") # 删除指定的session
# session.clear() # 删除所有session
return jsonify(msg=\"退出登录\")
app.run(host=\"0.0.0.0\")