Flask session/cookie操作

簡介

訪問者的標(biāo)識問題服務(wù)器需要識別來自同一訪問者的請求。這主要是通過瀏覽器的cookie實現(xiàn)的。 訪問者在第一次訪問服務(wù)器時,服務(wù)器在其cookie中設(shè)置一個唯一的ID號——會話ID(session)。 這樣,訪問者后續(xù)對服務(wù)器的訪問頭中將自動包含該信息,服務(wù)器通過這個ID號,即可區(qū) 隔不同的訪問者。

cookie

概念:

a. 客戶端會話技術(shù),瀏覽器的會話技術(shù)
b. 數(shù)據(jù)全部存儲在客戶端中
c. 存儲使用的鍵值對結(jié)構(gòu)進行存儲
特性:
? 支持過期時間
默認會自動攜帶本網(wǎng)站的cookie
不能跨域名
不能跨瀏覽器

創(chuàng)建:

Cookie是通過服務(wù)器創(chuàng)建的Response來創(chuàng)建的
設(shè)置: set_cookie('key', value, max_ages='', expires='')
刪除,有三種刪除方式

  1. 直接清空瀏覽器的cookie
  2. delete_cookie('key') 直接使用delete_cookie函數(shù)
  3. set_cookie('key', '', expires=0) 重新設(shè)置key的值為空,過期時間為0

獲取:

在每次請求中,url都會向服務(wù)器傳遞request,在request中可以獲取到cookie的信息
request.cookies.get('name')

例子1,設(shè)置cookie:

import datetime

@blue.route('/setcookie/')
def set_cookie():
    temp = render_template('index.html')
    response = make_response(temp)
    outdate = datetime.datetime.today() + datetime.timedelta(days=30)
    # 設(shè)置cookie中的name的存在時長,設(shè)置為30天才過期
    response.set_cookie('name', 'cocoococo', expires=outdate)
    return response

例子2, 刪除cookie中的值

@blue.route('/setcookie/')
def set_cookie():
    temp = render_template('index.html')
    response = make_response(temp)
    # 第一種方式,通過set_cookie去刪除
    response.set_cookie('name', '', expires=0)
    # 第二種凡是,del_cookie刪除
    response.del_cookie('name')
    return response

例子3, 獲取cookie中的值

@blue.route('/getcookie')
def get_cookie():
    name = request.cookies.get('name')
    
    return name

session

flask-session是flask框架的session組件
該組件則將支持session保存到多個地方
如:

redis
memcached
mongodb
sqlalchmey

安裝

pip install flask-session
如果指定存在session的類型為redis的話,需要安裝redis
pip install redis

語法

設(shè)置session:

session['key'] = value

讀取session:

result = session['key'] # 如果內(nèi)容不存在,將會報異常
result = session.get('key') #如果內(nèi)容不存在,將返回None

刪除session:

session.pop('key')

清空session中所有數(shù)據(jù):

session.clear()

使用

我們在初始化文件中創(chuàng)建一個方法,通過調(diào)用該方法來獲取到Flask的app對象

def create_app():
    app = Flask(__name__)
    # SECRET_KEY 秘鑰
    app.config['SECRET_KEY'] = 'secret_key'
    # session類型為redis
    app.config['SESSION_TYPE'] = 'redis'
    # 添加前綴
    app.config['SESSION_KEY_PREFIX'] = 'flask'
    
    # 加載app的第一種方式
    se = Session()
    se.init_app(app=app)
    #加載app的第二種方式
    Session(app=app)
    app.register_blueprint(blueprint=blue)

    return app

案例

定義一個登陸的方法,post請求獲取到username,直接寫入到redis中,并且在頁面中展示出redis中的username
a)需要先啟動redis,開啟redis-server,使用redis-cli進入客戶端
b)定義方法

@blue.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        username = session.get('username')
        return render_template('login.html', username=username)
    else:
        username = request.form.get('username')
        session['username'] = username

        return redirect(url_for('first.login'))

c)定義模板

<body>
<h3>歡迎:{{ username }}</h3>
<form action="" method="POST">
    用戶名:<input type="text" name="username" placeholder="請輸入你的名字">
    <input type="submit" value="提交">
</form>
</body>

d)redis中數(shù)據(jù)


image

注: 我們在定義app.config的時候訂了SESSION_KEY_PREFIX為flask,表示存在session中的key都會加一個前綴名flask

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容