local.py 8.4 KB

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