util.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. """Miscellaneous utility functions and classes.
  2. This module is used internally by Tornado. It is not necessarily expected
  3. that the functions and classes defined here will be useful to other
  4. applications, but they are documented here in case they are.
  5. The one public-facing part of this module is the `Configurable` class
  6. and its `~Configurable.configure` method, which becomes a part of the
  7. interface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,
  8. and `.Resolver`.
  9. """
  10. from __future__ import absolute_import, division, print_function, with_statement
  11. import array
  12. import os
  13. import sys
  14. import zlib
  15. try:
  16. xrange # py2
  17. except NameError:
  18. xrange = range # py3
  19. # inspect.getargspec() raises DeprecationWarnings in Python 3.5.
  20. # The two functions have compatible interfaces for the parts we need.
  21. try:
  22. from inspect import getfullargspec as getargspec # py3
  23. except ImportError:
  24. from inspect import getargspec # py2
  25. class ObjectDict(dict):
  26. """Makes a dictionary behave like an object, with attribute-style access.
  27. """
  28. def __getattr__(self, name):
  29. try:
  30. return self[name]
  31. except KeyError:
  32. raise AttributeError(name)
  33. def __setattr__(self, name, value):
  34. self[name] = value
  35. class GzipDecompressor(object):
  36. """Streaming gzip decompressor.
  37. The interface is like that of `zlib.decompressobj` (without some of the
  38. optional arguments, but it understands gzip headers and checksums.
  39. """
  40. def __init__(self):
  41. # Magic parameter makes zlib module understand gzip header
  42. # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib
  43. # This works on cpython and pypy, but not jython.
  44. self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  45. def decompress(self, value, max_length=None):
  46. """Decompress a chunk, returning newly-available data.
  47. Some data may be buffered for later processing; `flush` must
  48. be called when there is no more input data to ensure that
  49. all data was processed.
  50. If ``max_length`` is given, some input data may be left over
  51. in ``unconsumed_tail``; you must retrieve this value and pass
  52. it back to a future call to `decompress` if it is not empty.
  53. """
  54. return self.decompressobj.decompress(value, max_length)
  55. @property
  56. def unconsumed_tail(self):
  57. """Returns the unconsumed portion left over
  58. """
  59. return self.decompressobj.unconsumed_tail
  60. def flush(self):
  61. """Return any remaining buffered data not yet returned by decompress.
  62. Also checks for errors such as truncated input.
  63. No other methods may be called on this object after `flush`.
  64. """
  65. return self.decompressobj.flush()
  66. # Fake unicode literal support: Python 3.2 doesn't have the u'' marker for
  67. # literal strings, and alternative solutions like "from __future__ import
  68. # unicode_literals" have other problems (see PEP 414). u() can be applied
  69. # to ascii strings that include \u escapes (but they must not contain
  70. # literal non-ascii characters).
  71. if not isinstance(b'', type('')):
  72. def u(s):
  73. return s
  74. unicode_type = str
  75. basestring_type = str
  76. else:
  77. def u(s):
  78. return s.decode('unicode_escape')
  79. # These names don't exist in py3, so use noqa comments to disable
  80. # warnings in flake8.
  81. unicode_type = unicode # noqa
  82. basestring_type = basestring # noqa
  83. def import_object(name):
  84. """Imports an object by name.
  85. import_object('x') is equivalent to 'import x'.
  86. import_object('x.y.z') is equivalent to 'from x.y import z'.
  87. >>> import tornado.escape
  88. >>> import_object('tornado.escape') is tornado.escape
  89. True
  90. >>> import_object('tornado.escape.utf8') is tornado.escape.utf8
  91. True
  92. >>> import_object('tornado') is tornado
  93. True
  94. >>> import_object('tornado.missing_module')
  95. Traceback (most recent call last):
  96. ...
  97. ImportError: No module named missing_module
  98. """
  99. if isinstance(name, unicode_type) and str is not unicode_type:
  100. # On python 2 a byte string is required.
  101. name = name.encode('utf-8')
  102. if name.count('.') == 0:
  103. return __import__(name, None, None)
  104. parts = name.split('.')
  105. obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
  106. try:
  107. return getattr(obj, parts[-1])
  108. except AttributeError:
  109. raise ImportError("No module named %s" % parts[-1])
  110. # Deprecated alias that was used before we dropped py25 support.
  111. # Left here in case anyone outside Tornado is using it.
  112. bytes_type = bytes
  113. if sys.version_info > (3,):
  114. exec("""
  115. def raise_exc_info(exc_info):
  116. raise exc_info[1].with_traceback(exc_info[2])
  117. def exec_in(code, glob, loc=None):
  118. if isinstance(code, str):
  119. code = compile(code, '<string>', 'exec', dont_inherit=True)
  120. exec(code, glob, loc)
  121. """)
  122. else:
  123. exec("""
  124. def raise_exc_info(exc_info):
  125. raise exc_info[0], exc_info[1], exc_info[2]
  126. def exec_in(code, glob, loc=None):
  127. if isinstance(code, basestring):
  128. # exec(string) inherits the caller's future imports; compile
  129. # the string first to prevent that.
  130. code = compile(code, '<string>', 'exec', dont_inherit=True)
  131. exec code in glob, loc
  132. """)
  133. def errno_from_exception(e):
  134. """Provides the errno from an Exception object.
  135. There are cases that the errno attribute was not set so we pull
  136. the errno out of the args but if someone instantiates an Exception
  137. without any args you will get a tuple error. So this function
  138. abstracts all that behavior to give you a safe way to get the
  139. errno.
  140. """
  141. if hasattr(e, 'errno'):
  142. return e.errno
  143. elif e.args:
  144. return e.args[0]
  145. else:
  146. return None
  147. class Configurable(object):
  148. """Base class for configurable interfaces.
  149. A configurable interface is an (abstract) class whose constructor
  150. acts as a factory function for one of its implementation subclasses.
  151. The implementation subclass as well as optional keyword arguments to
  152. its initializer can be set globally at runtime with `configure`.
  153. By using the constructor as the factory method, the interface
  154. looks like a normal class, `isinstance` works as usual, etc. This
  155. pattern is most useful when the choice of implementation is likely
  156. to be a global decision (e.g. when `~select.epoll` is available,
  157. always use it instead of `~select.select`), or when a
  158. previously-monolithic class has been split into specialized
  159. subclasses.
  160. Configurable subclasses must define the class methods
  161. `configurable_base` and `configurable_default`, and use the instance
  162. method `initialize` instead of ``__init__``.
  163. """
  164. __impl_class = None
  165. __impl_kwargs = None
  166. def __new__(cls, *args, **kwargs):
  167. base = cls.configurable_base()
  168. init_kwargs = {}
  169. if cls is base:
  170. impl = cls.configured_class()
  171. if base.__impl_kwargs:
  172. init_kwargs.update(base.__impl_kwargs)
  173. else:
  174. impl = cls
  175. init_kwargs.update(kwargs)
  176. instance = super(Configurable, cls).__new__(impl)
  177. # initialize vs __init__ chosen for compatibility with AsyncHTTPClient
  178. # singleton magic. If we get rid of that we can switch to __init__
  179. # here too.
  180. instance.initialize(*args, **init_kwargs)
  181. return instance
  182. @classmethod
  183. def configurable_base(cls):
  184. """Returns the base class of a configurable hierarchy.
  185. This will normally return the class in which it is defined.
  186. (which is *not* necessarily the same as the cls classmethod parameter).
  187. """
  188. raise NotImplementedError()
  189. @classmethod
  190. def configurable_default(cls):
  191. """Returns the implementation class to be used if none is configured."""
  192. raise NotImplementedError()
  193. def initialize(self):
  194. """Initialize a `Configurable` subclass instance.
  195. Configurable classes should use `initialize` instead of ``__init__``.
  196. .. versionchanged:: 4.2
  197. Now accepts positional arguments in addition to keyword arguments.
  198. """
  199. @classmethod
  200. def configure(cls, impl, **kwargs):
  201. """Sets the class to use when the base class is instantiated.
  202. Keyword arguments will be saved and added to the arguments passed
  203. to the constructor. This can be used to set global defaults for
  204. some parameters.
  205. """
  206. base = cls.configurable_base()
  207. if isinstance(impl, (unicode_type, bytes)):
  208. impl = import_object(impl)
  209. if impl is not None and not issubclass(impl, cls):
  210. raise ValueError("Invalid subclass of %s" % cls)
  211. base.__impl_class = impl
  212. base.__impl_kwargs = kwargs
  213. @classmethod
  214. def configured_class(cls):
  215. """Returns the currently configured class."""
  216. base = cls.configurable_base()
  217. if cls.__impl_class is None:
  218. base.__impl_class = cls.configurable_default()
  219. return base.__impl_class
  220. @classmethod
  221. def _save_configuration(cls):
  222. base = cls.configurable_base()
  223. return (base.__impl_class, base.__impl_kwargs)
  224. @classmethod
  225. def _restore_configuration(cls, saved):
  226. base = cls.configurable_base()
  227. base.__impl_class = saved[0]
  228. base.__impl_kwargs = saved[1]
  229. class ArgReplacer(object):
  230. """Replaces one value in an ``args, kwargs`` pair.
  231. Inspects the function signature to find an argument by name
  232. whether it is passed by position or keyword. For use in decorators
  233. and similar wrappers.
  234. """
  235. def __init__(self, func, name):
  236. self.name = name
  237. try:
  238. self.arg_pos = self._getargnames(func).index(name)
  239. except ValueError:
  240. # Not a positional parameter
  241. self.arg_pos = None
  242. def _getargnames(self, func):
  243. try:
  244. return getargspec(func).args
  245. except TypeError:
  246. if hasattr(func, 'func_code'):
  247. # Cython-generated code has all the attributes needed
  248. # by inspect.getargspec, but the inspect module only
  249. # works with ordinary functions. Inline the portion of
  250. # getargspec that we need here. Note that for static
  251. # functions the @cython.binding(True) decorator must
  252. # be used (for methods it works out of the box).
  253. code = func.func_code
  254. return code.co_varnames[:code.co_argcount]
  255. raise
  256. def get_old_value(self, args, kwargs, default=None):
  257. """Returns the old value of the named argument without replacing it.
  258. Returns ``default`` if the argument is not present.
  259. """
  260. if self.arg_pos is not None and len(args) > self.arg_pos:
  261. return args[self.arg_pos]
  262. else:
  263. return kwargs.get(self.name, default)
  264. def replace(self, new_value, args, kwargs):
  265. """Replace the named argument in ``args, kwargs`` with ``new_value``.
  266. Returns ``(old_value, args, kwargs)``. The returned ``args`` and
  267. ``kwargs`` objects may not be the same as the input objects, or
  268. the input objects may be mutated.
  269. If the named argument was not found, ``new_value`` will be added
  270. to ``kwargs`` and None will be returned as ``old_value``.
  271. """
  272. if self.arg_pos is not None and len(args) > self.arg_pos:
  273. # The arg to replace is passed positionally
  274. old_value = args[self.arg_pos]
  275. args = list(args) # *args is normally a tuple
  276. args[self.arg_pos] = new_value
  277. else:
  278. # The arg to replace is either omitted or passed by keyword.
  279. old_value = kwargs.get(self.name)
  280. kwargs[self.name] = new_value
  281. return old_value, args, kwargs
  282. def timedelta_to_seconds(td):
  283. """Equivalent to td.total_seconds() (introduced in python 2.7)."""
  284. return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)
  285. def _websocket_mask_python(mask, data):
  286. """Websocket masking function.
  287. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
  288. Returns a `bytes` object of the same length as `data` with the mask applied
  289. as specified in section 5.3 of RFC 6455.
  290. This pure-python implementation may be replaced by an optimized version when available.
  291. """
  292. mask = array.array("B", mask)
  293. unmasked = array.array("B", data)
  294. for i in xrange(len(data)):
  295. unmasked[i] = unmasked[i] ^ mask[i % 4]
  296. if hasattr(unmasked, 'tobytes'):
  297. # tostring was deprecated in py32. It hasn't been removed,
  298. # but since we turn on deprecation warnings in our tests
  299. # we need to use the right one.
  300. return unmasked.tobytes()
  301. else:
  302. return unmasked.tostring()
  303. if (os.environ.get('TORNADO_NO_EXTENSION') or
  304. os.environ.get('TORNADO_EXTENSION') == '0'):
  305. # These environment variables exist to make it easier to do performance
  306. # comparisons; they are not guaranteed to remain supported in the future.
  307. _websocket_mask = _websocket_mask_python
  308. else:
  309. try:
  310. from tornado.speedups import websocket_mask as _websocket_mask
  311. except ImportError:
  312. if os.environ.get('TORNADO_EXTENSION') == '1':
  313. raise
  314. _websocket_mask = _websocket_mask_python
  315. def doctests():
  316. import doctest
  317. return doctest.DocTestSuite()