_cookiejar.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. """
  3. """
  4. _cookiejar.py
  5. websocket - WebSocket client library for Python
  6. Copyright 2021 engn33r
  7. Licensed under the Apache License, Version 2.0 (the "License");
  8. you may not use this file except in compliance with the License.
  9. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. """
  17. import http.cookies
  18. class SimpleCookieJar:
  19. def __init__(self):
  20. self.jar = dict()
  21. def add(self, set_cookie):
  22. if set_cookie:
  23. simpleCookie = http.cookies.SimpleCookie(set_cookie)
  24. for k, v in simpleCookie.items():
  25. domain = v.get("domain")
  26. if domain:
  27. if not domain.startswith("."):
  28. domain = "." + domain
  29. cookie = self.jar.get(domain) if self.jar.get(domain) else http.cookies.SimpleCookie()
  30. cookie.update(simpleCookie)
  31. self.jar[domain.lower()] = cookie
  32. def set(self, set_cookie):
  33. if set_cookie:
  34. simpleCookie = http.cookies.SimpleCookie(set_cookie)
  35. for k, v in simpleCookie.items():
  36. domain = v.get("domain")
  37. if domain:
  38. if not domain.startswith("."):
  39. domain = "." + domain
  40. self.jar[domain.lower()] = simpleCookie
  41. def get(self, host):
  42. if not host:
  43. return ""
  44. cookies = []
  45. for domain, simpleCookie in self.jar.items():
  46. host = host.lower()
  47. if host.endswith(domain) or host == domain[1:]:
  48. cookies.append(self.jar.get(domain))
  49. return "; ".join(filter(
  50. None, sorted(
  51. ["%s=%s" % (k, v.value) for cookie in filter(None, cookies) for k, v in cookie.items()]
  52. )))