Skip to content

Commit 6855638

Browse files
committed
feat: add cookie_utils
1 parent f7f3356 commit 6855638

2 files changed

Lines changed: 28 additions & 4 deletions

File tree

src/httpc/__main__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
from argparse import ArgumentParser
1010
import typing
1111

12+
from httpc.cookie_utils import cookie_json_to_raw
13+
1214
from ._base import __version__, logger
1315

1416
T = typing.TypeVar("T")
@@ -395,10 +397,7 @@ def _handle_cookies(args) -> None:
395397
text = Path(args.file).read_text("utf-8")
396398

397399
cookies = json.loads(text.strip())
398-
cookies_text = []
399-
for cookie in cookies:
400-
cookies_text.append(f'{cookie["name"]}={cookie["value"]}')
401-
value = "; ".join(cookies_text)
400+
value = cookie_json_to_raw(cookies)
402401

403402
print(json.dumps(value))
404403

src/httpc/cookie_utils.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from http.cookies import Morsel, SimpleCookie
2+
import typing
3+
4+
5+
def cookie_json_to_raw(cookies: dict, name: str = "name", value: str = "value") -> str:
6+
cookies_text = []
7+
for cookie in cookies:
8+
cookies_text.append(f'{cookie[name]}={cookie[value]}')
9+
return "; ".join(cookies_text)
10+
11+
12+
def cookie_dict_to_raw(cookies: dict[str, Morsel] | dict[str, str]) -> str:
13+
cookies_text = []
14+
for name, value in cookies.items():
15+
if isinstance(value, Morsel):
16+
value = value.coded_value
17+
cookies_text.append(f'{name}={value}')
18+
return "; ".join(cookies_text)
19+
20+
21+
def set_cookies(cookie_string: str, cookies: typing.Mapping[str, str] | dict[str, Morsel]) -> str:
22+
cookie = SimpleCookie(cookie_string)
23+
for name, value in cookies.items():
24+
cookie[name] = value
25+
return cookie_dict_to_raw(cookie)

0 commit comments

Comments
 (0)