1、设置和获取cookie
使用方法 | 描述 |
---|
response.set_cookie(“name”, “laowang”, max_age=3600) | 设置cookie |
request.cookies.get(“name”) | 获取cookie |
from flask import Flask, make_response, Response, request
app = Flask(__name__)
@app.route('/login')
def login():
"""
登录成功,通过响应对象设置cookie字典信息
:return:
"""
response = make_response("login success")
response.set_cookie("name", "laowang", max_age=3600)
return response
@app.route('/index')
def index():
"""
再次访问同一个浏览器,cookie会被自动携带上,通过请求对象提取cookie信息[字典]
:return:
"""
name = request.cookies.get("name")
print(name)
return "index page"
if __name__ == '__main__':
app.run(debug=True, port=8000)
2、设置和获取session
使用方法 | 描述 |
---|
session[“user_name”] = “Tom” | 设置session |
user_name = session.get(“user_name”) | 获取session |
from flask import Flask, session
from datetime import datetime, timedelta
app = Flask(__name__)
app.secret_key = "python39"
app.permanent_session_lifetime = timedelta(hours=2)
"""
session 本质就是一个字典,存储用户数据
session_id 发送给浏览器的【cookie机制】并且实现了数据加密
eyJ1c2VyX25hbWUiOiJqYW1lcyJ9.X5p7GQ.bhvxKPsKl_TqWXMItusriYytggE
注意:在flask中使用session必须指定加密字符串
"""
@app.route('/login')
def login():
"""
登录成功在session中存储用户信息
:return:
"""
session["user_name"] = "Tom"
session.permanent = True
return 'Hello World!'
@app.route('/index')
def index():
"""
再次访问同一个浏览器,提取session中用户信息
:return:
"""
user_name = session.get("user_name")
print(user_name)
return "index page"
if __name__ == '__main__':
app.run(debug=True, port=8000)
3、签发和获取校验jwt的token令牌
需求:使用jwt-token实现状态保持 [支持 html ios,安卓]
提前安装依赖包:pip install pyjwt
生成token:jwt.encode()
校验token:jwt.decode()
from flask import Flask, request
import jwt
from datetime import datetime, timedelta
app = Flask(__name__)
"""
需求:使用jwt-token实现状态保持 [支持 html ios,安卓]
提前:pip install pyjwt
生成token:jwt.encode()
校验token:jwt.decode()
"""
@app.route('/login')
def login():
"""
登录成功生成一个2小时有效的token
:return:
"""
expire = datetime.utcnow() + timedelta(hours=2)
payload = {
"user_id": 6,
"user_name": "Tom",
"exp": expire
}
key = "python3xxxx"
token = jwt.encode(payload=payload, key=key, algorithm="HS256")
token = token.decode()
print(token)
return token
@app.route('/profile')
def profile():
"""
获取前端在请求头中携带的token
header = {"Authorization": token}
:return:
"""
token = request.headers["Authorization"]
try:
payload = jwt.decode(token, key="python3xxxx", algorithms=["HS256"])
except Exception as e:
print(e)
payload = None
if payload:
user_id = payload.get("user_id")
user_name = payload.get("user_name")
return "profile: {}, {}".format(user_id, user_name)
else:
return "invalid token", 401
if __name__ == '__main__':
app.run(debug=True, port=8000)