# coding:utf-8 from flask import Flask, make_response, request app = Flask(__name__) @app.route("/set_cookie") def set_cookie(): # 建立一個響應的對象 resp = make_response('設置成功') # 設置cookie resp.set_cookie('username1', 'hannibal') # 設置多個cookie resp.set_cookie('username2', 'circle') # 默認的有效期是關閉瀏覽器以前 max_age 是手動添加有效期 單位是妙 resp.set_cookie('username3', 'benjamin', max_age=3600) return resp @app.route("/get_cookie") def get_cookie(): c = request.cookies.get('username1') return c @app.route('/del_cookie') def del_cookie():
# 刪除Cookie的時候也須要先建立響應對象 resp = make_response('del cookie') resp.delete_cookie('username3') return resp if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
resp.headers["Set-Cookie"] = "username3=benjamin; Expires=Tue, 23-Jul-2019 09:49:51 GMT; Max-Age=3600; Path=/"
session對象。它容許你在不一樣請求間存儲特定用戶的信息。它是在 Cookies 的基礎上實現的,而且對 Cookies 進行密鑰簽名。這意味着用戶能夠查看你 Cookie 的內容,但卻不能修改它,除非用戶知道簽名的密鑰。flask
>>> import os >>> os.urandom(24) 'u\x8a\r\x9b\x89\xad7//\xd6\x9a\x19\t\xdb3A\x92\xbaCN\xee\xc8x-'
# coding:utf-8 from flask import Flask, session, redirect, url_for, escape, request import sys reload(sys) sys.setdefaultencoding('utf8') app = Flask(__name__) # 設置密鑰 這個是必需要有的不然會拋出一個RuntimeError app.config['SECRET_KEY'] = 'u\x8a\r\x9b\x89\xad7//\xd6\x9a\x19\t\xdb3A\x92\xbaCN\xee\xc8x-' @app.route('/') def index(): if 'username' in session: print(session['username']) return '歡迎 %s 登錄' % escape(session['username']) return '抱歉你尚未登錄' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] # 重定向到index頁面 return redirect(url_for('index')) return ''' <form action="" method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' @app.route('/logout') def logout(): # 若是有就將它刪除 session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)