FLASK学习记录-Flask视图之Cookie&Session
Cookie
Cookie是网站辨别用户身份,进行会话跟踪而存储在用户本地终端上的数据,由用户客户端计算机暂时或永久保存。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask, request, make_response from datetime import datetime app = Flask(__name__) @app.route('/set_cookie') def set_cookie(): resp = make_response("create a cookie") resp.set_cookie("name1", "Anna") resp.set_cookie("name2", "Tom",expires=datetime(2024,3,28,16,30,00)) resp.set_cookie("name3", "Bob", max_age=3600) resp.headers["Set-Cookie"] = "name4=Sam;Max-Age=300" return resp @app.route('/get_cookie/<name>') def get_cookie(name): cookie = request.cookies.get(name) return cookie @app.route('/delete_cookie/<name>') def delete_cookie(name): resp = make_response('delete_cookie success') resp.delete_cookie(name) return resp if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)
http://xxx:8000/set_cookie/name1
http://xxx:8000/get_cookie/name3
http://xxx:8000/delete_cookie/name1
验证
Session
session是另一种记录客户状态的机制。区别在于cookie保存在客户端浏览器中,session保存在服务器上。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from flask import Flask, session from datetime import timedelta import os app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(12) app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=10) @app.route('/set_session') def set_session(): session['name'] = 'Jack' session.permanent = True return 'set session' @app.route('/get_session') def get_seesion(): return session.get('name') @app.route('/delete_session') def delete(): session.pop('name') return 'delete success' @app.route('/clear_session') def clear_session(): session.clear return 'clear success' if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)
http://xxxx:8000/set_session, http://xxxx:8000/get_session, http://xxxx:8000/delete_session, http://xxxx:8000/clear_session