/atom/url.py

http://radioappz.googlecode.com/ · Python · 139 lines · 91 code · 15 blank · 33 comment · 36 complexity · 8da1a83bd79ea061a97deba4de4afa3d MD5 · raw file

  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  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. __author__ = 'api.jscudder (Jeff Scudder)'
  17. import urlparse
  18. import urllib
  19. DEFAULT_PROTOCOL = 'http'
  20. DEFAULT_PORT = 80
  21. def parse_url(url_string):
  22. """Creates a Url object which corresponds to the URL string.
  23. This method can accept partial URLs, but it will leave missing
  24. members of the Url unset.
  25. """
  26. parts = urlparse.urlparse(url_string)
  27. url = Url()
  28. if parts[0]:
  29. url.protocol = parts[0]
  30. if parts[1]:
  31. host_parts = parts[1].split(':')
  32. if host_parts[0]:
  33. url.host = host_parts[0]
  34. if len(host_parts) > 1:
  35. url.port = host_parts[1]
  36. if parts[2]:
  37. url.path = parts[2]
  38. if parts[4]:
  39. param_pairs = parts[4].split('&')
  40. for pair in param_pairs:
  41. pair_parts = pair.split('=')
  42. if len(pair_parts) > 1:
  43. url.params[urllib.unquote_plus(pair_parts[0])] = (
  44. urllib.unquote_plus(pair_parts[1]))
  45. elif len(pair_parts) == 1:
  46. url.params[urllib.unquote_plus(pair_parts[0])] = None
  47. return url
  48. class Url(object):
  49. """Represents a URL and implements comparison logic.
  50. URL strings which are not identical can still be equivalent, so this object
  51. provides a better interface for comparing and manipulating URLs than
  52. strings. URL parameters are represented as a dictionary of strings, and
  53. defaults are used for the protocol (http) and port (80) if not provided.
  54. """
  55. def __init__(self, protocol=None, host=None, port=None, path=None,
  56. params=None):
  57. self.protocol = protocol
  58. self.host = host
  59. self.port = port
  60. self.path = path
  61. self.params = params or {}
  62. def to_string(self):
  63. url_parts = ['', '', '', '', '', '']
  64. if self.protocol:
  65. url_parts[0] = self.protocol
  66. if self.host:
  67. if self.port:
  68. url_parts[1] = ':'.join((self.host, str(self.port)))
  69. else:
  70. url_parts[1] = self.host
  71. if self.path:
  72. url_parts[2] = self.path
  73. if self.params:
  74. url_parts[4] = self.get_param_string()
  75. return urlparse.urlunparse(url_parts)
  76. def get_param_string(self):
  77. param_pairs = []
  78. for key, value in self.params.iteritems():
  79. param_pairs.append('='.join((urllib.quote_plus(key),
  80. urllib.quote_plus(str(value)))))
  81. return '&'.join(param_pairs)
  82. def get_request_uri(self):
  83. """Returns the path with the parameters escaped and appended."""
  84. param_string = self.get_param_string()
  85. if param_string:
  86. return '?'.join([self.path, param_string])
  87. else:
  88. return self.path
  89. def __cmp__(self, other):
  90. if not isinstance(other, Url):
  91. return cmp(self.to_string(), str(other))
  92. difference = 0
  93. # Compare the protocol
  94. if self.protocol and other.protocol:
  95. difference = cmp(self.protocol, other.protocol)
  96. elif self.protocol and not other.protocol:
  97. difference = cmp(self.protocol, DEFAULT_PROTOCOL)
  98. elif not self.protocol and other.protocol:
  99. difference = cmp(DEFAULT_PROTOCOL, other.protocol)
  100. if difference != 0:
  101. return difference
  102. # Compare the host
  103. difference = cmp(self.host, other.host)
  104. if difference != 0:
  105. return difference
  106. # Compare the port
  107. if self.port and other.port:
  108. difference = cmp(self.port, other.port)
  109. elif self.port and not other.port:
  110. difference = cmp(self.port, DEFAULT_PORT)
  111. elif not self.port and other.port:
  112. difference = cmp(DEFAULT_PORT, other.port)
  113. if difference != 0:
  114. return difference
  115. # Compare the path
  116. difference = cmp(self.path, other.path)
  117. if difference != 0:
  118. return difference
  119. # Compare the parameters
  120. return cmp(self.params, other.params)
  121. def __str__(self):
  122. return self.to_string()