local.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.local
  4. ~~~~~~~~~~~~
  5. This module contains critical utilities that
  6. needs to be loaded as soon as possible, and that
  7. shall not load any third party modules.
  8. Parts of this module is Copyright by Werkzeug Team.
  9. """
  10. from __future__ import absolute_import
  11. import importlib
  12. from .five import long_t, string
  13. __module__ = __name__ # used by Proxy class body
  14. def _default_cls_attr(name, type_, cls_value):
  15. # Proxy uses properties to forward the standard
  16. # class attributes __module__, __name__ and __doc__ to the real
  17. # object, but these needs to be a string when accessed from
  18. # the Proxy class directly. This is a hack to make that work.
  19. # -- See Issue #1087.
  20. def __new__(cls, getter):
  21. instance = type_.__new__(cls, cls_value)
  22. instance.__getter = getter
  23. return instance
  24. def __get__(self, obj, cls=None):
  25. return self.__getter(obj) if obj is not None else self
  26. return type(name, (type_, ), {
  27. '__new__': __new__, '__get__': __get__,
  28. })
  29. def try_import(module, default=None):
  30. """Try to import and return module, or return
  31. None if the module does not exist."""
  32. try:
  33. return importlib.import_module(module)
  34. except ImportError:
  35. return default
  36. class Proxy(object):
  37. """Proxy to another object."""
  38. # Code stolen from werkzeug.local.Proxy.
  39. __slots__ = ('__local', '__args', '__kwargs', '__dict__')
  40. def __init__(self, local, args=None, kwargs=None, name=None):
  41. object.__setattr__(self, '_Proxy__local', local)
  42. object.__setattr__(self, '_Proxy__args', args or ())
  43. object.__setattr__(self, '_Proxy__kwargs', kwargs or {})
  44. if name is not None:
  45. object.__setattr__(self, '__custom_name__', name)
  46. @_default_cls_attr('name', str, __name__)
  47. def __name__(self):
  48. try:
  49. return self.__custom_name__
  50. except AttributeError:
  51. return self._get_current_object().__name__
  52. @_default_cls_attr('module', str, __module__)
  53. def __module__(self):
  54. return self._get_current_object().__module__
  55. @_default_cls_attr('doc', str, __doc__)
  56. def __doc__(self):
  57. return self._get_current_object().__doc__
  58. def _get_class(self):
  59. return self._get_current_object().__class__
  60. @property
  61. def __class__(self):
  62. return self._get_class()
  63. def _get_current_object(self):
  64. """Return the current object. This is useful if you want the real
  65. object behind the proxy at a time for performance reasons or because
  66. you want to pass the object into a different context.
  67. """
  68. loc = object.__getattribute__(self, '_Proxy__local')
  69. if not hasattr(loc, '__release_local__'):
  70. return loc(*self.__args, **self.__kwargs)
  71. try:
  72. return getattr(loc, self.__name__)
  73. except AttributeError:
  74. raise RuntimeError('no object bound to {0.__name__}'.format(self))
  75. @property
  76. def __dict__(self):
  77. try:
  78. return self._get_current_object().__dict__
  79. except RuntimeError: # pragma: no cover
  80. raise AttributeError('__dict__')
  81. def __repr__(self):
  82. try:
  83. obj = self._get_current_object()
  84. except RuntimeError: # pragma: no cover
  85. return '<{0} unbound>'.format(self.__class__.__name__)
  86. return repr(obj)
  87. def __bool__(self):
  88. try:
  89. return bool(self._get_current_object())
  90. except RuntimeError: # pragma: no cover
  91. return False
  92. __nonzero__ = __bool__ # Py2
  93. def __unicode__(self):
  94. try:
  95. return string(self._get_current_object())
  96. except RuntimeError: # pragma: no cover
  97. return repr(self)
  98. def __dir__(self):
  99. try:
  100. return dir(self._get_current_object())
  101. except RuntimeError: # pragma: no cover
  102. return []
  103. def __getattr__(self, name):
  104. if name == '__members__':
  105. return dir(self._get_current_object())
  106. return getattr(self._get_current_object(), name)
  107. def __setitem__(self, key, value):
  108. self._get_current_object()[key] = value
  109. def __delitem__(self, key):
  110. del self._get_current_object()[key]
  111. def __setslice__(self, i, j, seq):
  112. self._get_current_object()[i:j] = seq
  113. def __delslice__(self, i, j):
  114. del self._get_current_object()[i:j]
  115. __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
  116. __delattr__ = lambda x, n: delattr(x._get_current_object(), n)
  117. __str__ = lambda x: str(x._get_current_object())
  118. __lt__ = lambda x, o: x._get_current_object() < o
  119. __le__ = lambda x, o: x._get_current_object() <= o
  120. __eq__ = lambda x, o: x._get_current_object() == o
  121. __ne__ = lambda x, o: x._get_current_object() != o
  122. __gt__ = lambda x, o: x._get_current_object() > o
  123. __ge__ = lambda x, o: x._get_current_object() >= o
  124. __cmp__ = lambda x, o: cmp(x._get_current_object(), o)
  125. __hash__ = lambda x: hash(x._get_current_object())
  126. __call__ = lambda x, *a, **kw: x._get_current_object()(*a, **kw)
  127. __len__ = lambda x: len(x._get_current_object())
  128. __getitem__ = lambda x, i: x._get_current_object()[i]
  129. __iter__ = lambda x: iter(x._get_current_object())
  130. __contains__ = lambda x, i: i in x._get_current_object()
  131. __getslice__ = lambda x, i, j: x._get_current_object()[i:j]
  132. __add__ = lambda x, o: x._get_current_object() + o
  133. __sub__ = lambda x, o: x._get_current_object() - o
  134. __mul__ = lambda x, o: x._get_current_object() * o
  135. __floordiv__ = lambda x, o: x._get_current_object() // o
  136. __mod__ = lambda x, o: x._get_current_object() % o
  137. __divmod__ = lambda x, o: x._get_current_object().__divmod__(o)
  138. __pow__ = lambda x, o: x._get_current_object() ** o
  139. __lshift__ = lambda x, o: x._get_current_object() << o
  140. __rshift__ = lambda x, o: x._get_current_object() >> o
  141. __and__ = lambda x, o: x._get_current_object() & o
  142. __xor__ = lambda x, o: x._get_current_object() ^ o
  143. __or__ = lambda x, o: x._get_current_object() | o
  144. __div__ = lambda x, o: x._get_current_object().__div__(o)
  145. __truediv__ = lambda x, o: x._get_current_object().__truediv__(o)
  146. __neg__ = lambda x: -(x._get_current_object())
  147. __pos__ = lambda x: +(x._get_current_object())
  148. __abs__ = lambda x: abs(x._get_current_object())
  149. __invert__ = lambda x: ~(x._get_current_object())
  150. __complex__ = lambda x: complex(x._get_current_object())
  151. __int__ = lambda x: int(x._get_current_object())
  152. __long__ = lambda x: long_t(x._get_current_object())
  153. __float__ = lambda x: float(x._get_current_object())
  154. __oct__ = lambda x: oct(x._get_current_object())
  155. __hex__ = lambda x: hex(x._get_current_object())
  156. __index__ = lambda x: x._get_current_object().__index__()
  157. __coerce__ = lambda x, o: x._get_current_object().__coerce__(o)
  158. __enter__ = lambda x: x._get_current_object().__enter__()
  159. __exit__ = lambda x, *a, **kw: x._get_current_object().__exit__(*a, **kw)
  160. __reduce__ = lambda x: x._get_current_object().__reduce__()
  161. class PromiseProxy(Proxy):
  162. """This is a proxy to an object that has not yet been evaulated.
  163. :class:`Proxy` will evaluate the object each time, while the
  164. promise will only evaluate it once.
  165. """
  166. def _get_current_object(self):
  167. try:
  168. return object.__getattribute__(self, '__thing')
  169. except AttributeError:
  170. return self.__evaluate__()
  171. def __evaluated__(self):
  172. try:
  173. object.__getattribute__(self, '__thing')
  174. except AttributeError:
  175. return False
  176. return True
  177. def __maybe_evaluate__(self):
  178. return self._get_current_object()
  179. def __evaluate__(self,
  180. _clean=('_Proxy__local',
  181. '_Proxy__args',
  182. '_Proxy__kwargs')):
  183. try:
  184. thing = Proxy._get_current_object(self)
  185. object.__setattr__(self, '__thing', thing)
  186. return thing
  187. finally:
  188. for attr in _clean:
  189. try:
  190. object.__delattr__(self, attr)
  191. except AttributeError: # pragma: no cover
  192. # May mask errors so ignore
  193. pass
  194. def maybe_evaluate(obj):
  195. try:
  196. return obj.__maybe_evaluate__()
  197. except AttributeError:
  198. return obj