Django教程

Django Cookies处理

Django Cookies处理详细操作教程
有时候,可能要按您的Web应用程序的要求存储访问者一些数据在每个站点。始终牢记,那cookies被保存在客户端,并根据您的客户端浏览器的安全级别,设置cookie 存活的时间,有时候可能不需要。
为了说明在Django如何cookie处理,让我们创建一个使用之前创建的登录功能的系统。 系统将让你登录为时间x分钟,在此时间之后,应用程序将会自动注销你的登陆信息。
对于这一点,需要设置两个cookie:last_connection和username。
首先,让我们改变登录视图以存储用户名和last_connection cookies −
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
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秒内 −
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
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,配对新的视图 −
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-23
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)。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4