PageRenderTime 30ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/telemetry/third_party/gsutilz/third_party/protorpc/protorpc/util.py

https://gitlab.com/jonnialva90/iridium-browser
Python | 492 lines | 461 code | 12 blank | 19 comment | 0 complexity | cb329ee72af32c8fec5d9436b835c7eb MD5 | raw file
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2010 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. #
  17. """Common utility library."""
  18. from __future__ import with_statement
  19. import six
  20. __author__ = ['rafek@google.com (Rafe Kaplan)',
  21. 'guido@google.com (Guido van Rossum)',
  22. ]
  23. import cgi
  24. import datetime
  25. import inspect
  26. import os
  27. import re
  28. import sys
  29. __all__ = ['AcceptItem',
  30. 'AcceptError',
  31. 'Error',
  32. 'choose_content_type',
  33. 'decode_datetime',
  34. 'get_package_for_module',
  35. 'pad_string',
  36. 'parse_accept_header',
  37. 'positional',
  38. 'PROTORPC_PROJECT_URL',
  39. 'TimeZoneOffset',
  40. 'total_seconds',
  41. ]
  42. class Error(Exception):
  43. """Base class for protorpc exceptions."""
  44. class AcceptError(Error):
  45. """Raised when there is an error parsing the accept header."""
  46. PROTORPC_PROJECT_URL = 'http://code.google.com/p/google-protorpc'
  47. _TIME_ZONE_RE_STRING = r"""
  48. # Examples:
  49. # +01:00
  50. # -05:30
  51. # Z12:00
  52. ((?P<z>Z) | (?P<sign>[-+])
  53. (?P<hours>\d\d) :
  54. (?P<minutes>\d\d))$
  55. """
  56. _TIME_ZONE_RE = re.compile(_TIME_ZONE_RE_STRING, re.IGNORECASE | re.VERBOSE)
  57. def pad_string(string):
  58. """Pad a string for safe HTTP error responses.
  59. Prevents Internet Explorer from displaying their own error messages
  60. when sent as the content of error responses.
  61. Args:
  62. string: A string.
  63. Returns:
  64. Formatted string left justified within a 512 byte field.
  65. """
  66. return string.ljust(512)
  67. def positional(max_positional_args):
  68. """A decorator to declare that only the first N arguments may be positional.
  69. This decorator makes it easy to support Python 3 style keyword-only
  70. parameters. For example, in Python 3 it is possible to write:
  71. def fn(pos1, *, kwonly1=None, kwonly1=None):
  72. ...
  73. All named parameters after * must be a keyword:
  74. fn(10, 'kw1', 'kw2') # Raises exception.
  75. fn(10, kwonly1='kw1') # Ok.
  76. Example:
  77. To define a function like above, do:
  78. @positional(1)
  79. def fn(pos1, kwonly1=None, kwonly2=None):
  80. ...
  81. If no default value is provided to a keyword argument, it becomes a required
  82. keyword argument:
  83. @positional(0)
  84. def fn(required_kw):
  85. ...
  86. This must be called with the keyword parameter:
  87. fn() # Raises exception.
  88. fn(10) # Raises exception.
  89. fn(required_kw=10) # Ok.
  90. When defining instance or class methods always remember to account for
  91. 'self' and 'cls':
  92. class MyClass(object):
  93. @positional(2)
  94. def my_method(self, pos1, kwonly1=None):
  95. ...
  96. @classmethod
  97. @positional(2)
  98. def my_method(cls, pos1, kwonly1=None):
  99. ...
  100. One can omit the argument to 'positional' altogether, and then no
  101. arguments with default values may be passed positionally. This
  102. would be equivalent to placing a '*' before the first argument
  103. with a default value in Python 3. If there are no arguments with
  104. default values, and no argument is given to 'positional', an error
  105. is raised.
  106. @positional
  107. def fn(arg1, arg2, required_kw1=None, required_kw2=0):
  108. ...
  109. fn(1, 3, 5) # Raises exception.
  110. fn(1, 3) # Ok.
  111. fn(1, 3, required_kw1=5) # Ok.
  112. Args:
  113. max_positional_arguments: Maximum number of positional arguments. All
  114. parameters after the this index must be keyword only.
  115. Returns:
  116. A decorator that prevents using arguments after max_positional_args from
  117. being used as positional parameters.
  118. Raises:
  119. TypeError if a keyword-only argument is provided as a positional parameter.
  120. ValueError if no maximum number of arguments is provided and the function
  121. has no arguments with default values.
  122. """
  123. def positional_decorator(wrapped):
  124. def positional_wrapper(*args, **kwargs):
  125. if len(args) > max_positional_args:
  126. plural_s = ''
  127. if max_positional_args != 1:
  128. plural_s = 's'
  129. raise TypeError('%s() takes at most %d positional argument%s '
  130. '(%d given)' % (wrapped.__name__,
  131. max_positional_args,
  132. plural_s, len(args)))
  133. return wrapped(*args, **kwargs)
  134. return positional_wrapper
  135. if isinstance(max_positional_args, six.integer_types):
  136. return positional_decorator
  137. else:
  138. args, _, _, defaults = inspect.getargspec(max_positional_args)
  139. if defaults is None:
  140. raise ValueError(
  141. 'Functions with no keyword arguments must specify '
  142. 'max_positional_args')
  143. return positional(len(args) - len(defaults))(max_positional_args)
  144. # TODO(rafek): Support 'level' from the Accept header standard.
  145. class AcceptItem(object):
  146. """Encapsulate a single entry of an Accept header.
  147. Parses and extracts relevent values from an Accept header and implements
  148. a sort order based on the priority of each requested type as defined
  149. here:
  150. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  151. Accept headers are normally a list of comma separated items. Each item
  152. has the format of a normal HTTP header. For example:
  153. Accept: text/plain, text/html, text/*, */*
  154. This header means to prefer plain text over HTML, HTML over any other
  155. kind of text and text over any other kind of supported format.
  156. This class does not attempt to parse the list of items from the Accept header.
  157. The constructor expects the unparsed sub header and the index within the
  158. Accept header that the fragment was found.
  159. Properties:
  160. index: The index that this accept item was found in the Accept header.
  161. main_type: The main type of the content type.
  162. sub_type: The sub type of the content type.
  163. q: The q value extracted from the header as a float. If there is no q
  164. value, defaults to 1.0.
  165. values: All header attributes parsed form the sub-header.
  166. sort_key: A tuple (no_main_type, no_sub_type, q, no_values, index):
  167. no_main_type: */* has the least priority.
  168. no_sub_type: Items with no sub-type have less priority.
  169. q: Items with lower q value have less priority.
  170. no_values: Items with no values have less priority.
  171. index: Index of item in accept header is the last priority.
  172. """
  173. __CONTENT_TYPE_REGEX = re.compile(r'^([^/]+)/([^/]+)$')
  174. def __init__(self, accept_header, index):
  175. """Parse component of an Accept header.
  176. Args:
  177. accept_header: Unparsed sub-expression of accept header.
  178. index: The index that this accept item was found in the Accept header.
  179. """
  180. accept_header = accept_header.lower()
  181. content_type, values = cgi.parse_header(accept_header)
  182. match = self.__CONTENT_TYPE_REGEX.match(content_type)
  183. if not match:
  184. raise AcceptError('Not valid Accept header: %s' % accept_header)
  185. self.__index = index
  186. self.__main_type = match.group(1)
  187. self.__sub_type = match.group(2)
  188. self.__q = float(values.get('q', 1))
  189. self.__values = values
  190. if self.__main_type == '*':
  191. self.__main_type = None
  192. if self.__sub_type == '*':
  193. self.__sub_type = None
  194. self.__sort_key = (not self.__main_type,
  195. not self.__sub_type,
  196. -self.__q,
  197. not self.__values,
  198. self.__index)
  199. @property
  200. def index(self):
  201. return self.__index
  202. @property
  203. def main_type(self):
  204. return self.__main_type
  205. @property
  206. def sub_type(self):
  207. return self.__sub_type
  208. @property
  209. def q(self):
  210. return self.__q
  211. @property
  212. def values(self):
  213. """Copy the dictionary of values parsed from the header fragment."""
  214. return dict(self.__values)
  215. @property
  216. def sort_key(self):
  217. return self.__sort_key
  218. def match(self, content_type):
  219. """Determine if the given accept header matches content type.
  220. Args:
  221. content_type: Unparsed content type string.
  222. Returns:
  223. True if accept header matches content type, else False.
  224. """
  225. content_type, _ = cgi.parse_header(content_type)
  226. match = self.__CONTENT_TYPE_REGEX.match(content_type.lower())
  227. if not match:
  228. return False
  229. main_type, sub_type = match.group(1), match.group(2)
  230. if not(main_type and sub_type):
  231. return False
  232. return ((self.__main_type is None or self.__main_type == main_type) and
  233. (self.__sub_type is None or self.__sub_type == sub_type))
  234. def __cmp__(self, other):
  235. """Comparison operator based on sort keys."""
  236. if not isinstance(other, AcceptItem):
  237. return NotImplemented
  238. return cmp(self.sort_key, other.sort_key)
  239. def __str__(self):
  240. """Rebuilds Accept header."""
  241. content_type = '%s/%s' % (self.__main_type or '*', self.__sub_type or '*')
  242. values = self.values
  243. if values:
  244. value_strings = ['%s=%s' % (i, v) for i, v in values.items()]
  245. return '%s; %s' % (content_type, '; '.join(value_strings))
  246. else:
  247. return content_type
  248. def __repr__(self):
  249. return 'AcceptItem(%r, %d)' % (str(self), self.__index)
  250. def parse_accept_header(accept_header):
  251. """Parse accept header.
  252. Args:
  253. accept_header: Unparsed accept header. Does not include name of header.
  254. Returns:
  255. List of AcceptItem instances sorted according to their priority.
  256. """
  257. accept_items = []
  258. for index, header in enumerate(accept_header.split(',')):
  259. accept_items.append(AcceptItem(header, index))
  260. return sorted(accept_items)
  261. def choose_content_type(accept_header, supported_types):
  262. """Choose most appropriate supported type based on what client accepts.
  263. Args:
  264. accept_header: Unparsed accept header. Does not include name of header.
  265. supported_types: List of content-types supported by the server. The index
  266. of the supported types determines which supported type is prefered by
  267. the server should the accept header match more than one at the same
  268. priority.
  269. Returns:
  270. The preferred supported type if the accept header matches any, else None.
  271. """
  272. for accept_item in parse_accept_header(accept_header):
  273. for supported_type in supported_types:
  274. if accept_item.match(supported_type):
  275. return supported_type
  276. return None
  277. @positional(1)
  278. def get_package_for_module(module):
  279. """Get package name for a module.
  280. Helper calculates the package name of a module.
  281. Args:
  282. module: Module to get name for. If module is a string, try to find
  283. module in sys.modules.
  284. Returns:
  285. If module contains 'package' attribute, uses that as package name.
  286. Else, if module is not the '__main__' module, the module __name__.
  287. Else, the base name of the module file name. Else None.
  288. """
  289. if isinstance(module, six.string_types):
  290. try:
  291. module = sys.modules[module]
  292. except KeyError:
  293. return None
  294. try:
  295. return six.text_type(module.package)
  296. except AttributeError:
  297. if module.__name__ == '__main__':
  298. try:
  299. file_name = module.__file__
  300. except AttributeError:
  301. pass
  302. else:
  303. base_name = os.path.basename(file_name)
  304. split_name = os.path.splitext(base_name)
  305. if len(split_name) == 1:
  306. return six.text_type(base_name)
  307. else:
  308. return u'.'.join(split_name[:-1])
  309. return six.text_type(module.__name__)
  310. def total_seconds(offset):
  311. """Backport of offset.total_seconds() from python 2.7+."""
  312. seconds = offset.days * 24 * 60 * 60 + offset.seconds
  313. microseconds = seconds * 10**6 + offset.microseconds
  314. return microseconds / (10**6 * 1.0)
  315. class TimeZoneOffset(datetime.tzinfo):
  316. """Time zone information as encoded/decoded for DateTimeFields."""
  317. def __init__(self, offset):
  318. """Initialize a time zone offset.
  319. Args:
  320. offset: Integer or timedelta time zone offset, in minutes from UTC. This
  321. can be negative.
  322. """
  323. super(TimeZoneOffset, self).__init__()
  324. if isinstance(offset, datetime.timedelta):
  325. offset = total_seconds(offset) / 60
  326. self.__offset = offset
  327. def utcoffset(self, dt):
  328. """Get the a timedelta with the time zone's offset from UTC.
  329. Returns:
  330. The time zone offset from UTC, as a timedelta.
  331. """
  332. return datetime.timedelta(minutes=self.__offset)
  333. def dst(self, dt):
  334. """Get the daylight savings time offset.
  335. The formats that ProtoRPC uses to encode/decode time zone information don't
  336. contain any information about daylight savings time. So this always
  337. returns a timedelta of 0.
  338. Returns:
  339. A timedelta of 0.
  340. """
  341. return datetime.timedelta(0)
  342. def decode_datetime(encoded_datetime):
  343. """Decode a DateTimeField parameter from a string to a python datetime.
  344. Args:
  345. encoded_datetime: A string in RFC 3339 format.
  346. Returns:
  347. A datetime object with the date and time specified in encoded_datetime.
  348. Raises:
  349. ValueError: If the string is not in a recognized format.
  350. """
  351. # Check if the string includes a time zone offset. Break out the
  352. # part that doesn't include time zone info. Convert to uppercase
  353. # because all our comparisons should be case-insensitive.
  354. time_zone_match = _TIME_ZONE_RE.search(encoded_datetime)
  355. if time_zone_match:
  356. time_string = encoded_datetime[:time_zone_match.start(1)].upper()
  357. else:
  358. time_string = encoded_datetime.upper()
  359. if '.' in time_string:
  360. format_string = '%Y-%m-%dT%H:%M:%S.%f'
  361. else:
  362. format_string = '%Y-%m-%dT%H:%M:%S'
  363. decoded_datetime = datetime.datetime.strptime(time_string, format_string)
  364. if not time_zone_match:
  365. return decoded_datetime
  366. # Time zone info was included in the parameter. Add a tzinfo
  367. # object to the datetime. Datetimes can't be changed after they're
  368. # created, so we'll need to create a new one.
  369. if time_zone_match.group('z'):
  370. offset_minutes = 0
  371. else:
  372. sign = time_zone_match.group('sign')
  373. hours, minutes = [int(value) for value in
  374. time_zone_match.group('hours', 'minutes')]
  375. offset_minutes = hours * 60 + minutes
  376. if sign == '-':
  377. offset_minutes *= -1
  378. return datetime.datetime(decoded_datetime.year,
  379. decoded_datetime.month,
  380. decoded_datetime.day,
  381. decoded_datetime.hour,
  382. decoded_datetime.minute,
  383. decoded_datetime.second,
  384. decoded_datetime.microsecond,
  385. TimeZoneOffset(offset_minutes))