local.py 8.5 KB

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