您好,登錄后才能下訂單哦!
本文實例講述了Django項目開發中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']
設置cookies:
response.set_cookie('<cookie_name>', value)
獲取session:
fav_color = request.session.get('fav_color', 'red') fav_color = request.session['fav_color']
設置session:
request.session['visits'] = visits
刪除session:
del request.session['fav_color']
如果給出的key 在會話中不存在,將拋出 KeyError。
判斷包含session:
'fav_color' in request.session
清除session數據庫
python manage.py clearsessions
附:Django基于自定義cookies 的登錄,注冊,退出功能示例:
#注冊 def regist(req): if req.method == 'POST': uf = UserForm(req.POST) if uf.is_valid(): #獲得表單數據 username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] #添加到數據庫 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'] #獲取的表單數據與數據庫進行比較 user = User.objects.filter(username__exact = username,password__exact = password) if user: #比較成功,跳轉index response = HttpResponseRedirect('/online/index/') #將username寫入瀏覽器cookie,失效時間為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程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。