您好,登錄后才能下訂單哦!
本文實(shí)例講述了Django項(xiàng)目開發(fā)中cookies和session的常用操作。分享給大家供大家參考,具體如下:
檢查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:
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ì)有所幫助。
免責(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)容。