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