Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/websocket/_cookiejar.py: 27%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

33 statements  

1import http.cookies 

2from typing import Optional 

3 

4""" 

5_cookiejar.py 

6websocket - WebSocket client library for Python 

7 

8Copyright 2024 engn33r 

9 

10Licensed under the Apache License, Version 2.0 (the "License"); 

11you may not use this file except in compliance with the License. 

12You may obtain a copy of the License at 

13 

14 http://www.apache.org/licenses/LICENSE-2.0 

15 

16Unless required by applicable law or agreed to in writing, software 

17distributed under the License is distributed on an "AS IS" BASIS, 

18WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

19See the License for the specific language governing permissions and 

20limitations under the License. 

21""" 

22 

23 

24class SimpleCookieJar: 

25 def __init__(self) -> None: 

26 self.jar: dict = {} 

27 

28 def add(self, set_cookie: Optional[str]) -> None: 

29 if set_cookie: 

30 simple_cookie = http.cookies.SimpleCookie(set_cookie) 

31 

32 for v in simple_cookie.values(): 

33 if domain := v.get("domain"): 

34 if not domain.startswith("."): 

35 domain = f".{domain}" 

36 cookie = ( 

37 self.jar.get(domain) 

38 if self.jar.get(domain) 

39 else http.cookies.SimpleCookie() 

40 ) 

41 cookie.update(simple_cookie) 

42 self.jar[domain.lower()] = cookie 

43 

44 def set(self, set_cookie: str) -> None: 

45 if set_cookie: 

46 simple_cookie = http.cookies.SimpleCookie(set_cookie) 

47 

48 for v in simple_cookie.values(): 

49 if domain := v.get("domain"): 

50 if not domain.startswith("."): 

51 domain = f".{domain}" 

52 self.jar[domain.lower()] = simple_cookie 

53 

54 def get(self, host: str) -> str: 

55 if not host: 

56 return "" 

57 

58 cookies = [] 

59 for domain, _ in self.jar.items(): 

60 host = host.lower() 

61 if host.endswith(domain) or host == domain[1:]: 

62 cookies.append(self.jar.get(domain)) 

63 

64 return "; ".join( 

65 filter( 

66 None, 

67 sorted( 

68 [ 

69 f"{k}={v.value}" 

70 for cookie in filter(None, cookies) 

71 for k, v in cookie.items() 

72 ] 

73 ), 

74 ) 

75 )