Skip to content

Commit a7eb145

Browse files
authored
Merge pull request #1 from mic1on/perf_utils
🎈 perf(utils): `cookie_to_dict` `headers_to_dict` `data_to_dict`
2 parents 1ba4c5c + f40f238 commit a7eb145

File tree

3 files changed

+19
-16
lines changed

3 files changed

+19
-16
lines changed

example/use_to.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33

44
def demo_to():
55
print("demo_to")
6-
print(useTo.to_string('https://www.baidu.com'))
7-
print(useTo.to_string(b'https://www.baidu.com'))
8-
print(useTo.to_string(123))
9-
print(useTo.to_string(123.456))
10-
print(useTo.to_string(True))
11-
print(useTo.to_string(None))
12-
print(useTo.to_string([1, 2, 3]))
13-
print(useTo.to_string({'a': 1, 'b': 2, 'c': 3}))
6+
print(useTo.string('https://www.baidu.com'))
7+
print(useTo.string(b'https://www.baidu.com'))
8+
print(useTo.string(123))
9+
print(useTo.string(123.456))
10+
print(useTo.string(True))
11+
print(useTo.string(None))
12+
print(useTo.string([1, 2, 3]))
13+
print(useTo.string({'a': 1, 'b': 2, 'c': 3}))
1414
pass
1515

1616

src/usepy/utils/utils.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def cookie_to_dict(cookies: str) -> dict:
1313
:param cookies: cookie字符串
1414
:return: dict
1515
"""
16-
return {cookie.split('=')[0]: cookie.split('=')[-1] for cookie in cookies.split('; ')}
16+
return dict(x.split('=') for x in cookies.split('; ')) # noqa
1717

1818

1919
def headers_to_dict(headers: str) -> dict:
@@ -22,12 +22,7 @@ def headers_to_dict(headers: str) -> dict:
2222
:param headers: headers字符串
2323
:return: dict
2424
"""
25-
header_dict = {}
26-
for line in headers.split('\n'):
27-
if ':' in line:
28-
key, value = line.split(':', 1)
29-
header_dict[key.strip()] = value.strip()
30-
return header_dict
25+
return dict(map(lambda x: x.strip(), line.split(':')) for line in headers.split('\n') if ':' in line) # noqa
3126

3227

3328
def data_to_dict(data: str) -> dict:
@@ -36,7 +31,7 @@ def data_to_dict(data: str) -> dict:
3631
:param data: data字符串。格式为`key1=value1&key2=value2`
3732
:return: dict
3833
"""
39-
return {item.split('=')[0]: item.split('=')[-1] for item in data.split('&')}
34+
return dict(x.split('=') for x in data.split('&')) # noqa
4035

4136

4237
def gen_unique_id():

tests/test_utils/test_utils.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@ def test_cookie_to_dict():
3333
}
3434

3535

36+
def test_data_to_dict():
37+
data_str = "key1=value1&key2=value2"
38+
assert useDataToDict(data_str) == {
39+
"key1": "value1",
40+
"key2": "value2",
41+
}
42+
43+
3644
def test_header_to_dict():
3745
header_str = """sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"
3846
sec-ch-ua-platform: "macOS"

0 commit comments

Comments
 (0)