_cookiejar.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """
  2. """
  3. """
  4. websocket - WebSocket client library for Python
  5. Copyright (C) 2010 Hiroki Ohtani(liris)
  6. This library is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU Lesser General Public
  8. License as published by the Free Software Foundation; either
  9. version 2.1 of the License, or (at your option) any later version.
  10. This library is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. Lesser General Public License for more details.
  14. You should have received a copy of the GNU Lesser General Public
  15. License along with this library; if not, write to the Free Software
  16. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. """
  18. try:
  19. import Cookie
  20. except:
  21. import http.cookies as Cookie
  22. class SimpleCookieJar(object):
  23. def __init__(self):
  24. self.jar = dict()
  25. def add(self, set_cookie):
  26. if set_cookie:
  27. try:
  28. simpleCookie = Cookie.SimpleCookie(set_cookie)
  29. except:
  30. simpleCookie = Cookie.SimpleCookie(set_cookie.encode('ascii', 'ignore'))
  31. for k, v in simpleCookie.items():
  32. domain = v.get("domain")
  33. if domain:
  34. if not domain.startswith("."):
  35. domain = "." + domain
  36. cookie = self.jar.get(domain) if self.jar.get(domain) else Cookie.SimpleCookie()
  37. cookie.update(simpleCookie)
  38. self.jar[domain.lower()] = cookie
  39. def set(self, set_cookie):
  40. if set_cookie:
  41. try:
  42. simpleCookie = Cookie.SimpleCookie(set_cookie)
  43. except:
  44. simpleCookie = Cookie.SimpleCookie(set_cookie.encode('ascii', 'ignore'))
  45. for k, v in simpleCookie.items():
  46. domain = v.get("domain")
  47. if domain:
  48. if not domain.startswith("."):
  49. domain = "." + domain
  50. self.jar[domain.lower()] = simpleCookie
  51. def get(self, host):
  52. if not host:
  53. return ""
  54. cookies = []
  55. for domain, simpleCookie in self.jar.items():
  56. host = host.lower()
  57. if host.endswith(domain) or host == domain[1:]:
  58. cookies.append(self.jar.get(domain))
  59. return "; ".join(filter(
  60. None, sorted(
  61. ["%s=%s" % (k, v.value) for cookie in filter(None, cookies) for k, v in cookie.items()]
  62. )))