Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

local.py 11KB

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