Fix cookie parser (change to Django way)

This commit is contained in:
Yaser Amiri 2018-02-18 16:37:20 +03:30
parent 7e4a9e3bc2
commit 4cd7276bb6
2 changed files with 27 additions and 7 deletions

View File

@ -3,7 +3,7 @@ import json
import socket import socket
from cgi import parse_header from cgi import parse_header
from collections import namedtuple from collections import namedtuple
from http.cookies import SimpleCookie from http import cookies
from httptools import parse_url from httptools import parse_url
from urllib.parse import parse_qs, urlunparse from urllib.parse import parse_qs, urlunparse
@ -158,15 +158,20 @@ class Request(dict):
def cookies(self): def cookies(self):
if self._cookies is None: if self._cookies is None:
cookie = self.headers.get('Cookie') cookie = self.headers.get('Cookie')
self._cookies = {}
if cookie is not None: if cookie is not None:
cookies = SimpleCookie() for chunk in cookie.split(';'):
cookies.load(cookie) if '=' in chunk:
self._cookies = {name: cookie.value key, val = chunk.split('=', 1)
for name, cookie in cookies.items()} else:
else: key, val = '', chunk
self._cookies = {} key, val = key.strip(), val.strip()
if key or val:
self._cookies[key] = cookies._unquote(val)
return self._cookies return self._cookies
@property @property
def ip(self): def ip(self):
if not hasattr(self, '_socket'): if not hasattr(self, '_socket'):

View File

@ -113,3 +113,18 @@ def test_cookie_deletion():
assert int(response_cookies['i_want_to_die']['max-age']) == 0 assert int(response_cookies['i_want_to_die']['max-age']) == 0
with pytest.raises(KeyError): with pytest.raises(KeyError):
hold_my_beer = response.cookies['i_never_existed'] 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'