溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django項(xiàng)目開發(fā)中cookies和session的常用操作分析

發(fā)布時(shí)間:2020-09-30 20:05:07 來源:腳本之家 閱讀:139 作者:win_turn 欄目:開發(fā)技術(shù)

本文實(shí)例講述了Django項(xiàng)目開發(fā)中cookies和session的常用操作。分享給大家供大家參考,具體如下:

COOKIES操作

檢查cookies是否存在:

request.COOKIES.has_key('<cookie_name>')

獲取cookies:

request.COOKIES.get('visits', '1')
if 'last_visit' in request.COOKIES:
 request.COOKIES['last_visit']

設(shè)置cookies:

response.set_cookie('<cookie_name>', value)

SESSION操作

獲取session:

fav_color = request.session.get('fav_color', 'red')
fav_color = request.session['fav_color']

設(shè)置session:

request.session['visits'] = visits

刪除session:

del request.session['fav_color']

如果給出的key 在會(huì)話中不存在,將拋出 KeyError。

判斷包含session:

'fav_color' in request.session

清除session數(shù)據(jù)庫

python manage.py clearsessions

附:Django基于自定義cookies 的登錄,注冊,退出功能示例:

#注冊
def regist(req):
  if req.method == 'POST':
    uf = UserForm(req.POST)
    if uf.is_valid():
      #獲得表單數(shù)據(jù)
      username = uf.cleaned_data['username']
      password = uf.cleaned_data['password']
      #添加到數(shù)據(jù)庫
      User.objects.create(username= username,password=password)
      return HttpResponse('regist success!!')
  else:
    uf = UserForm()
  return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(req))
#登陸
def login(req):
  if req.method == 'POST':
    uf = UserForm(req.POST)
    if uf.is_valid():
      #獲取表單用戶密碼
      username = uf.cleaned_data['username']
      password = uf.cleaned_data['password']
      #獲取的表單數(shù)據(jù)與數(shù)據(jù)庫進(jìn)行比較
      user = User.objects.filter(username__exact = username,password__exact = password)
      if user:
        #比較成功,跳轉(zhuǎn)index
        response = HttpResponseRedirect('/online/index/')
        #將username寫入瀏覽器cookie,失效時(shí)間為3600
        response.set_cookie('username',username,3600)
        return response
      else:
        #比較失敗,還在login
        return HttpResponseRedirect('/online/login/')
  else:
    uf = UserForm()
  return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
#登陸成功
def index(req):
  username = req.COOKIES.get('username','')
  return render_to_response('index.html' ,{'username':username})
#退出
def logout(req):
  response = HttpResponse('logout !!')
  #清理cookie里保存username
  response.delete_cookie('username')
  return response

希望本文所述對大家基于Django框架的Python程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI