Django 简明教程

Django - Cookies Handling

有时候,你可能希望根据 Web 应用程序的要求按每个网站访问者的基础存储一些数据。始终记住,Cookie 存储在客户端,并且根据客户端浏览器安全级别,设置 Cookie 有时会起作用,有时可能不会。

Sometimes you might want to store some data on a per-site-visitor basis as per the requirements of your web application. Always keep in mind, that cookies are saved on the client side and depending on your client browser security level, setting cookies can at times work and at times might not.

为了说明 Django 中的 Cookie 处理,让我们使用之前创建的登录系统创建一个系统。该系统会让你继续登录 X 分钟,在此时间之后,你将退出应用。

To illustrate cookies handling in Django, let’s create a system using the login system we created before. The system will keep you logged in for X minute of time, and beyond that time, you will be out of the app.

为此,你需要设置两个 Cookie,即 last_connection 和 username。

For this, you will need to set up two cookies, last_connection and username.

首先,让我们更改我们的登录视图来存储我们的 username 和 last_connection Cookie −

At first, let’s change our login view to store our username and 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 是通过对响应(而不是请求)调用的 set_cookie 方法完成的,还需要注意的是,所有 Cookie 值都作为字符串返回。

As seen in the view above, setting cookie is done by the set_cookie method called on the response not the request, and also note that all cookies values are returned as string.

现在,让我们为登录创建 formView,其中当 Cookie 设置且不早于 10 秒时,我们将不会显示表单 −

Let’s now create a formView for the login form, where we won’t display the form if cookie is set and is not older than 10 second −

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 中所示,你可以通过请求的 COOKIES 属性(dict)来访问设置的 Cookie。

As you can see in the formView above accessing the cookie you set, is done via the COOKIES attribute (dict) of the request.

现在,让我们更改 url.py 文件来更改 URL,使其与我们的新视图配对 −

Now let’s change the url.py file to change the URL so it pairs with our new view −

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 时,你将获得以下页面 −

When accessing /myapp/connection, you will get the following page −

django cookies handling

在提交后,你将被重定向到以下屏幕 −

And you will get redirected to the following screen on submit −

cookies handling redirected page

现在,如果 10 秒内再次尝试访问 /myapp/connection,您将被直接重定向到第二个屏幕。如果您在这个范围之外再次访问 /myapp/connection,您将看到登录表单(屏幕 1)。

Now, if you try to access /myapp/connection again in the 10 seconds range, you will get redirected to the second screen directly. And if you access /myapp/connection again out of this range you will get the login form (screen 1).