淺析Django中關于session的使用
一、Session的概念
cookie是在瀏覽器端保存鍵值對數(shù)據(jù),而session是在服務器端保存鍵值對數(shù)據(jù)
session 的使用依賴 cookie:在使用Session后,會在Cookie中存儲一個sessionid的數(shù)據(jù),每次請求時瀏覽器都會將這個數(shù)據(jù)發(fā)給服務器,服務器在接收到sessionid后,會根據(jù)這個值找出這個請求者的Session。
二、Django中session的使用
session鍵值對數(shù)據(jù)保存
session數(shù)據(jù)默認保存在django項目的一張數(shù)據(jù)庫表中(表名為:django_session),保存格式如下:
三、數(shù)據(jù)操作:
以鍵值對的格式寫session
request.session['鍵']=值
根據(jù)鍵讀取值
request.session.get('鍵',默認值) # 或者 request.session['鍵']
清除所有session,在存儲中刪除值的部分
request.session.clear()
清除session數(shù)據(jù),在存儲中刪除session的整條數(shù)據(jù)
request.session.flush()
刪除session中的指定鍵及值,在存儲中只刪除某個鍵及對應的值
del request.session['鍵']
設置session數(shù)據(jù)有效時間; 如果不設置,默認過期時間為兩周
request.session.set_expiry(value)
- 如果value是一個整數(shù),則 session數(shù)據(jù) 將在value秒沒有活動后過期。
- 如果value為None,那么會話永不過期。
- 如果value為0,那么用戶會話的Cookie將在用戶的瀏覽器關閉時過期。
四、以下是使用例子:
# 發(fā)短信接口 def sms_send(request): # http://localhost:8000/duanxin/duanxin/sms_send/?phone=18434288349 # 1 獲取手機號 phone = request.GET.get('phone') # 2 生成6位驗證碼 code = aliyunsms.get_code(6, False) # 3 緩存到Redis #cache.set(phone,code,60) #60s有效期 #print('判斷緩存中是否有:',cache.has_key(phone)) #print('獲取Redis驗證碼:',cache.get(phone)) #暫時用session處理 request.session['phone'] = code request.session.set_expiry(300) #設置5分鐘后過期 print('判斷緩存中是否有:', request.session.get('phone')) print('獲取session驗證碼:',request.session.get('phone')) # 4 發(fā)短信 result = aliyunsms.send_sms(phone, code) return HttpResponse(result) # 短信驗證碼校驗 def sms_check(request): # /duanxin/sms_check/?phone=xxx&code=xxx # 1. 電話和手動輸入的驗證碼 phone = request.GET.get('phone') code = request.GET.get('code') # 2. 獲取redis中保存的code #print('緩存中是否包含:',cache.has_key(phone)) #print('取值:',cache.get(phone)) #cache_code = cache.get(phone) #獲取session里的code print('取值:', request.session.get('phone')) cache_code = request.session.get('phone') # 3. 判斷 if code == cache_code: return HttpResponse(json.dumps({'result':'OK'})) else: return HttpResponse(json.dumps({'result':'False'}))
總結
以上所述是小編給大家介紹的Django下關于session的使用,希望對大家有所幫助!
相關文章
Python中報錯 “TypeError: ‘list‘ object is&n
這篇文章主要介紹了Python中報錯 “TypeError: ‘list‘ object is not callable”問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09