Django Cookies處理

有時候,可能要按您的Web應用程式的要求存儲訪問者一些數據在每個站點。始終牢記,那cookies被保存在客戶端,並根據您的客戶端流覽器的安全級別,設置cookie 存活的時間,有時候可能不需要。

為了說明在Django如何cookie處理,讓我們創建一個使用之前創建的登錄功能的系統。 系統將讓你登錄為時間x分鐘,在此時間之後,應用程式將會自動註銷你的登陸資訊。

對於這一點,需要設置兩個cookie:last_connection和username。

首先,讓我們改變登錄視圖以存儲用戶名和last_connection cookies −

from django.template import RequestContext

def login(request):
   username = "not logged in"

   if request.method == "POST":
      #Get the posted form
      MyLoginForm = LoginForm(request.POST)

   if MyLoginForm.is_valid():
      username = MyLoginForm.cleaned_data['username']
   else:
      MyLoginForm = LoginForm()

   response = render_to_response(request, 'loggedin.html', {"username" : username},
      context_instance = RequestContext(request))

   response.set_cookie('last_connection', datetime.datetime.now())
   response.set_cookie('username', datetime.datetime.now())

   return response 

正如在上面這個視圖,設置cookie是調用setcookie方法完成的,而不是請求回應的, 還要注意所有Cookie的值是作為字串返回的。

讓我們為登錄表單創建一個FormView,我們將不會顯示的表單,如果Cookie設置並且在10秒內 −

def formView(request):
   if 'username' in request.COOKIES and 'last_connection' in request.COOKIES:
      username = request.COOKIES['username']

      last_connection = request.COOKIES['last_connection']
      last_connection_time = datetime.datetime.strptime(last_connection[:-7],
         "%Y-%m-%d %H:%M:%S")

      if (datetime.datetime.now() - last_connection_time).seconds < 10:
         return render(request, 'loggedin.html', {"username" : username})
      else:
         return render(request, 'login.html', {})

   else:
      return render(request, 'login.html', {}) 

可以在 formView 視圖上訪問您設置Cookie,通過請求COOKIES類屬性(字典)完成。

現在修改url.py檔更改URL,配對新的視圖 −

from django.conf.urls import patterns, url
from django.views.generic import TemplateView

urlpatterns = patterns('myapp.views',
   url(r'^connection/','formView', name = 'loginform'),
   url(r'^login/', 'login', name = 'login'))
當訪問 /myapp/connection,您將進入以下頁面-

提交後會重定向到以下介面 -

現在,如果你在10秒內訪問 /myapp/connection 一遍, 會得到直接重定向到第二個螢幕。如果你再次訪問 /myapp/connection 超出這個範圍,將會得到的登錄表單(螢幕1)。



上一篇: Django Apache配置 下一篇: Django Session會話