diff --git a/pydu/request.py b/pydu/request.py index a7c8e18..a04e499 100644 --- a/pydu/request.py +++ b/pydu/request.py @@ -139,21 +139,18 @@ def update_query_params(url, params): return new_url -def cookies_string_to_dict(cookies_string): +def cookies_str_to_dict(cookies): """ - Transform cookies which is type of string to the type of dict + Convert cookies from str to dict. """ - if not cookies_string or cookies_string == '': - raise ValueError("Invalid blank param of cookies_string !") - if not isinstance(cookies_string, str): - raise TypeError("Invalid type of cookies_string !") - cookies_dict = {} - for single_mapping_item in cookies_string.split(";"): - single_mapping_item = single_mapping_item.strip().replace("\t", "").replace("\n", "") - if '=' not in single_mapping_item: + if not isinstance(cookies, str): + raise TypeError('Invalid type of cookies_string !') + + cookies_obj = {} + for item in cookies.split(';'): + item = item.strip().replace('\t', '').replace('\n', '') + if '=' not in item: continue - kv_list = single_mapping_item.split('=') - if len(kv_list) == 0: - continue - cookies_dict[kv_list[0]] = kv_list[1] - return cookies_dict \ No newline at end of file + key, value = item.split('=', 1) + cookies_obj[key] = value + return cookies_obj diff --git a/stubs/pydu/request.pyi b/stubs/pydu/request.pyi index 94bd354..ab153b8 100644 --- a/stubs/pydu/request.pyi +++ b/stubs/pydu/request.pyi @@ -12,4 +12,4 @@ class FileName(object): def download(url: str, dst: str=None) -> str: ... def check_connect(ip: str, port: int, retry: int=1, timout: float=0.5) -> Optional[str]: ... def update_query_params(url: str, params: dict) -> str: ... -def cookies_string_to_dict(cookies_string: str) -> dict: ... +def cookies_str_to_dict(cookies: str) -> dict: ... diff --git a/tests/test_request.py b/tests/test_request.py index 56a0dce..1877d56 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -2,7 +2,7 @@ import socket from .testing import mockserver import pydu.request from pydu.network import get_free_port -from pydu.request import FileName, check_connect, update_query_params, cookies_string_to_dict +from pydu.request import FileName, check_connect, update_query_params, cookies_str_to_dict def test_filename_from_url(): @@ -62,10 +62,9 @@ def test_update_query_params(): (base + '?foo=2&bar=3', base + '?bar=3&foo=2') -def test_cookies_string_to_dict(): - cookies_string = """ - _ga=GA1.2.129780172.1530933530; _gid=GA1.2.1377057427.1530933530; ajs_anonymous_id=%228c887ac4-df75-4251-bd83-453dffab984f%22; - """ - cookies_dict = cookies_string_to_dict(cookies_string=cookies_string) - assert cookies_dict is not None - assert isinstance(cookies_dict, dict) +def test_cookies_str_to_dict(): + cookies = cookies_str_to_dict('a=a; \tb=b;\nc=c;d;e=') + assert cookies['a'] == 'a' + assert cookies['b'] == 'b' + assert cookies['c'] == 'c' + assert cookies['e'] == ''