Fix cookie parser (change to Django way)
This commit is contained in:
parent
7e4a9e3bc2
commit
4cd7276bb6
|
@ -3,7 +3,7 @@ import json
|
|||
import socket
|
||||
from cgi import parse_header
|
||||
from collections import namedtuple
|
||||
from http.cookies import SimpleCookie
|
||||
from http import cookies
|
||||
from httptools import parse_url
|
||||
from urllib.parse import parse_qs, urlunparse
|
||||
|
||||
|
@ -158,15 +158,20 @@ class Request(dict):
|
|||
def cookies(self):
|
||||
if self._cookies is None:
|
||||
cookie = self.headers.get('Cookie')
|
||||
self._cookies = {}
|
||||
if cookie is not None:
|
||||
cookies = SimpleCookie()
|
||||
cookies.load(cookie)
|
||||
self._cookies = {name: cookie.value
|
||||
for name, cookie in cookies.items()}
|
||||
else:
|
||||
self._cookies = {}
|
||||
for chunk in cookie.split(';'):
|
||||
if '=' in chunk:
|
||||
key, val = chunk.split('=', 1)
|
||||
else:
|
||||
key, val = '', chunk
|
||||
key, val = key.strip(), val.strip()
|
||||
if key or val:
|
||||
self._cookies[key] = cookies._unquote(val)
|
||||
|
||||
return self._cookies
|
||||
|
||||
|
||||
@property
|
||||
def ip(self):
|
||||
if not hasattr(self, '_socket'):
|
||||
|
|
|
@ -113,3 +113,18 @@ def test_cookie_deletion():
|
|||
assert int(response_cookies['i_want_to_die']['max-age']) == 0
|
||||
with pytest.raises(KeyError):
|
||||
hold_my_beer = response.cookies['i_never_existed']
|
||||
|
||||
|
||||
def test_cookie_parsing():
|
||||
app = Sanic('test_text')
|
||||
|
||||
@app.route('/')
|
||||
def handler(request):
|
||||
test_1 = request.cookies.get('test_1')
|
||||
test_2 = request.cookies.get('test_2')
|
||||
return json({'test_1': test_1, 'test_2': test_2})
|
||||
|
||||
headers = {'cookie': 'test_1=t1; test_2=t 2'}
|
||||
request, response = app.test_client.get('/', headers=headers)
|
||||
assert response.json['test_1'] == 't1'
|
||||
assert response.json['test_2'] == 't 2'
|
||||
|
|
Loading…
Reference in New Issue
Block a user