多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
django提供了一些方法对cookie进行操作,主要分为以下三个内容: - 设置cookie - 删除cookie - 获取cookie ### 设置cookie 设置key和value等参数可以给浏览器设置cookie,在django中,需要对response对象进行操作 设置cookie可以通过`response.set_cookie`来设置 ```python def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_aware(expires): expires = timezone.make_naive(expires, timezone.utc) delta = expires - expires.utcnow() # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). delta = delta + datetime.timedelta(seconds=1) # Just set max_age - the max_age logic will set expires. expires = None max_age = max(0, delta.days * 86400 + delta.seconds) else: self.cookies[key]['expires'] = expires else: self.cookies[key]['expires'] = '' if max_age is not None: self.cookies[key]['max-age'] = max_age # IE requires expires, so set it if hasn't been already. if not expires: self.cookies[key]['expires'] = cookie_date(time.time() + max_age) if path is not None: self.cookies[key]['path'] = path if domain is not None: self.cookies[key]['domain'] = domain if secure: self.cookies[key]['secure'] = True if httponly: self.cookies[key]['httponly'] = True ``` `set_cookie`中一共有8个参数,分别如下: 1. key :这个 cookie 的 key 。 2. value :这个 cookie 的 value 。 3. max_age :最长的生命周期。单位是秒。 4. expires :过期时间。跟 max_age 是类似的,只不过这个参数需要传递一个具体的日期,比如 datetime 或者是符合日期格式的字符串。如果同时设置了 expires 和 max_age ,那么将会使用 expires 的值作为过期时间。 5. path :对域名下哪个路径有效。默认是对域名下所有路径都有效。 6. domain :针对哪个域名有效。默认是针对主域名下都有效,如果只要针对某个子域名才有效,那么可以设置这个属性. 7. secure :是否是安全的,如果设置为 True ,那么只能在 https 协议下才可用。 8. httponly :默认是 False 。如果为 True ,那么在客户端不能通过 JavaScript对cookie进行操作。 #### 设置cookie例子 ##### 设置key-value 在`vews.py`中添加以下代码 ```python from django.http import HttpResponse def index(request): response = HttpResponse('index') response.set_cookie('username', 'zhiliao') return response ``` 在`urls.py`中设置路由 ```python from . import views path('', views.index), ``` 然后运行django ### 删除cookie 通过`delete_cookie` 方法即可删除 cookie ```python def delete_cookie(self, key, path='/', domain=None): self.set_cookie(key, max_age=0, path=path, domain=domain, expires='Thu, 01-Jan-1970 00:00:00 GMT') ``` 实际上删除 cookie 就是将指定的 cookie 的值设置为空的字符串,然后使用将他的过期时间设置为 0 ,也就是浏览器关闭后就过期 ### 获取cookie