PageRenderTime 80ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/test_auth/django/utils/http.py

https://bitbucket.org/atmaramshetye/test
Python | 226 lines | 189 code | 6 blank | 31 comment | 3 complexity | d2022ed18ad95ba78cec4313c9167b0f MD5 | raw file
Possible License(s): BSD-3-Clause
  1. import calendar
  2. import datetime
  3. import re
  4. import sys
  5. import urllib
  6. import urlparse
  7. from email.utils import formatdate
  8. from django.utils.datastructures import MultiValueDict
  9. from django.utils.encoding import smart_str, force_unicode
  10. from django.utils.functional import allow_lazy
  11. ETAG_MATCH = re.compile(r'(?:W/)?"((?:\\.|[^"])*)"')
  12. MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split()
  13. __D = r'(?P<day>\d{2})'
  14. __D2 = r'(?P<day>[ \d]\d)'
  15. __M = r'(?P<mon>\w{3})'
  16. __Y = r'(?P<year>\d{4})'
  17. __Y2 = r'(?P<year>\d{2})'
  18. __T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})'
  19. RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T))
  20. RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
  21. ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
  22. def urlquote(url, safe='/'):
  23. """
  24. A version of Python's urllib.quote() function that can operate on unicode
  25. strings. The url is first UTF-8 encoded before quoting. The returned string
  26. can safely be used as part of an argument to a subsequent iri_to_uri() call
  27. without double-quoting occurring.
  28. """
  29. return force_unicode(urllib.quote(smart_str(url), smart_str(safe)))
  30. urlquote = allow_lazy(urlquote, unicode)
  31. def urlquote_plus(url, safe=''):
  32. """
  33. A version of Python's urllib.quote_plus() function that can operate on
  34. unicode strings. The url is first UTF-8 encoded before quoting. The
  35. returned string can safely be used as part of an argument to a subsequent
  36. iri_to_uri() call without double-quoting occurring.
  37. """
  38. return force_unicode(urllib.quote_plus(smart_str(url), smart_str(safe)))
  39. urlquote_plus = allow_lazy(urlquote_plus, unicode)
  40. def urlunquote(quoted_url):
  41. """
  42. A wrapper for Python's urllib.unquote() function that can operate on
  43. the result of django.utils.http.urlquote().
  44. """
  45. return force_unicode(urllib.unquote(smart_str(quoted_url)))
  46. urlunquote = allow_lazy(urlunquote, unicode)
  47. def urlunquote_plus(quoted_url):
  48. """
  49. A wrapper for Python's urllib.unquote_plus() function that can operate on
  50. the result of django.utils.http.urlquote_plus().
  51. """
  52. return force_unicode(urllib.unquote_plus(smart_str(quoted_url)))
  53. urlunquote_plus = allow_lazy(urlunquote_plus, unicode)
  54. def urlencode(query, doseq=0):
  55. """
  56. A version of Python's urllib.urlencode() function that can operate on
  57. unicode strings. The parameters are first case to UTF-8 encoded strings and
  58. then encoded as per normal.
  59. """
  60. if isinstance(query, MultiValueDict):
  61. query = query.lists()
  62. elif hasattr(query, 'items'):
  63. query = query.items()
  64. return urllib.urlencode(
  65. [(smart_str(k),
  66. isinstance(v, (list,tuple)) and [smart_str(i) for i in v] or smart_str(v))
  67. for k, v in query],
  68. doseq)
  69. def cookie_date(epoch_seconds=None):
  70. """
  71. Formats the time to ensure compatibility with Netscape's cookie standard.
  72. Accepts a floating point number expressed in seconds since the epoch, in
  73. UTC - such as that outputted by time.time(). If set to None, defaults to
  74. the current time.
  75. Outputs a string in the format 'Wdy, DD-Mon-YYYY HH:MM:SS GMT'.
  76. """
  77. rfcdate = formatdate(epoch_seconds)
  78. return '%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25])
  79. def http_date(epoch_seconds=None):
  80. """
  81. Formats the time to match the RFC1123 date format as specified by HTTP
  82. RFC2616 section 3.3.1.
  83. Accepts a floating point number expressed in seconds since the epoch, in
  84. UTC - such as that outputted by time.time(). If set to None, defaults to
  85. the current time.
  86. Outputs a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'.
  87. """
  88. rfcdate = formatdate(epoch_seconds)
  89. return '%s GMT' % rfcdate[:25]
  90. def parse_http_date(date):
  91. """
  92. Parses a date format as specified by HTTP RFC2616 section 3.3.1.
  93. The three formats allowed by the RFC are accepted, even if only the first
  94. one is still in widespread use.
  95. Returns an floating point number expressed in seconds since the epoch, in
  96. UTC.
  97. """
  98. # emails.Util.parsedate does the job for RFC1123 dates; unfortunately
  99. # RFC2616 makes it mandatory to support RFC850 dates too. So we roll
  100. # our own RFC-compliant parsing.
  101. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
  102. m = regex.match(date)
  103. if m is not None:
  104. break
  105. else:
  106. raise ValueError("%r is not in a valid HTTP date format" % date)
  107. try:
  108. year = int(m.group('year'))
  109. if year < 100:
  110. if year < 70:
  111. year += 2000
  112. else:
  113. year += 1900
  114. month = MONTHS.index(m.group('mon').lower()) + 1
  115. day = int(m.group('day'))
  116. hour = int(m.group('hour'))
  117. min = int(m.group('min'))
  118. sec = int(m.group('sec'))
  119. result = datetime.datetime(year, month, day, hour, min, sec)
  120. return calendar.timegm(result.utctimetuple())
  121. except Exception:
  122. raise ValueError("%r is not a valid date" % date)
  123. def parse_http_date_safe(date):
  124. """
  125. Same as parse_http_date, but returns None if the input is invalid.
  126. """
  127. try:
  128. return parse_http_date(date)
  129. except Exception:
  130. pass
  131. # Base 36 functions: useful for generating compact URLs
  132. def base36_to_int(s):
  133. """
  134. Converts a base 36 string to an ``int``. Raises ``ValueError` if the
  135. input won't fit into an int.
  136. """
  137. # To prevent overconsumption of server resources, reject any
  138. # base36 string that is long than 13 base36 digits (13 digits
  139. # is sufficient to base36-encode any 64-bit integer)
  140. if len(s) > 13:
  141. raise ValueError("Base36 input too large")
  142. value = int(s, 36)
  143. # ... then do a final check that the value will fit into an int.
  144. if value > sys.maxint:
  145. raise ValueError("Base36 input too large")
  146. return value
  147. def int_to_base36(i):
  148. """
  149. Converts an integer to a base36 string
  150. """
  151. digits = "0123456789abcdefghijklmnopqrstuvwxyz"
  152. factor = 0
  153. if not 0 <= i <= sys.maxint:
  154. raise ValueError("Base36 conversion input too large or incorrect type.")
  155. # Find starting factor
  156. while True:
  157. factor += 1
  158. if i < 36 ** factor:
  159. factor -= 1
  160. break
  161. base36 = []
  162. # Construct base36 representation
  163. while factor >= 0:
  164. j = 36 ** factor
  165. base36.append(digits[i // j])
  166. i = i % j
  167. factor -= 1
  168. return ''.join(base36)
  169. def parse_etags(etag_str):
  170. """
  171. Parses a string with one or several etags passed in If-None-Match and
  172. If-Match headers by the rules in RFC 2616. Returns a list of etags
  173. without surrounding double quotes (") and unescaped from \<CHAR>.
  174. """
  175. etags = ETAG_MATCH.findall(etag_str)
  176. if not etags:
  177. # etag_str has wrong format, treat it as an opaque string then
  178. return [etag_str]
  179. etags = [e.decode('string_escape') for e in etags]
  180. return etags
  181. def quote_etag(etag):
  182. """
  183. Wraps a string in double quotes escaping contents as necesary.
  184. """
  185. return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')
  186. if sys.version_info >= (2, 6):
  187. def same_origin(url1, url2):
  188. """
  189. Checks if two URLs are 'same-origin'
  190. """
  191. p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2)
  192. return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port)
  193. else:
  194. # Python 2.5 compatibility. This actually works for Python 2.6 and above,
  195. # but the above definition is much more obviously correct and so is
  196. # preferred going forward.
  197. def same_origin(url1, url2):
  198. """
  199. Checks if two URLs are 'same-origin'
  200. """
  201. p1, p2 = urlparse.urlparse(url1), urlparse.urlparse(url2)
  202. return p1[0:2] == p2[0:2]