local.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. # -*- coding: utf-8 -*-
  2. """Proxy/PromiseProxy implementation.
  3. This module contains critical utilities that needs to be loaded as
  4. soon as possible, and that shall not load any third party modules.
  5. Parts of this module is Copyright by Werkzeug Team.
  6. """
  7. from __future__ import absolute_import, unicode_literals
  8. import operator
  9. import sys
  10. from functools import reduce
  11. from importlib import import_module
  12. from types import ModuleType
  13. from .five import PY3, bytes_if_py2, items, string, string_t
  14. __all__ = ('Proxy', 'PromiseProxy', 'try_import', 'maybe_evaluate')
  15. __module__ = __name__ # used by Proxy class body
  16. def _default_cls_attr(name, type_, cls_value):
  17. # Proxy uses properties to forward the standard
  18. # class attributes __module__, __name__ and __doc__ to the real
  19. # object, but these needs to be a string when accessed from
  20. # the Proxy class directly. This is a hack to make that work.
  21. # -- See Issue #1087.
  22. def __new__(cls, getter):
  23. instance = type_.__new__(cls, cls_value)
  24. instance.__getter = getter
  25. return instance
  26. def __get__(self, obj, cls=None):
  27. return self.__getter(obj) if obj is not None else self
  28. return type(bytes_if_py2(name), (type_,), {
  29. '__new__': __new__, '__get__': __get__,
  30. })
  31. def try_import(module, default=None):
  32. """Try to import and return module.
  33. Returns None if the module does not exist.
  34. """
  35. try:
  36. return 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('qualname', str, __name__)
  59. def __qualname__(self):
  60. try:
  61. return self.__custom_name__
  62. except AttributeError:
  63. return self._get_current_object().__qualname__
  64. @_default_cls_attr('module', str, __module__)
  65. def __module__(self):
  66. return self._get_current_object().__module__
  67. @_default_cls_attr('doc', str, __doc__)
  68. def __doc__(self):
  69. return self._get_current_object().__doc__
  70. def _get_class(self):
  71. return self._get_current_object().__class__
  72. @property
  73. def __class__(self):
  74. return self._get_class()
  75. def _get_current_object(self):
  76. """Get current object.
  77. This is useful if you want the real
  78. object behind the proxy at a time for performance reasons or because
  79. you want to pass the object into a different context.
  80. """
  81. loc = object.__getattribute__(self, '_Proxy__local')
  82. if not hasattr(loc, '__release_local__'):
  83. return loc(*self.__args, **self.__kwargs)
  84. try: # pragma: no cover
  85. # not sure what this is about
  86. return getattr(loc, self.__name__)
  87. except AttributeError: # pragma: no cover
  88. raise RuntimeError('no object bound to {0.__name__}'.format(self))
  89. @property
  90. def __dict__(self):
  91. try:
  92. return self._get_current_object().__dict__
  93. except RuntimeError: # pragma: no cover
  94. raise AttributeError('__dict__')
  95. def __repr__(self):
  96. try:
  97. obj = self._get_current_object()
  98. except RuntimeError: # pragma: no cover
  99. return '<{0} unbound>'.format(self.__class__.__name__)
  100. return repr(obj)
  101. def __bool__(self):
  102. try:
  103. return bool(self._get_current_object())
  104. except RuntimeError: # pragma: no cover
  105. return False
  106. __nonzero__ = __bool__ # Py2
  107. def __dir__(self):
  108. try:
  109. return dir(self._get_current_object())
  110. except RuntimeError: # pragma: no cover
  111. return []
  112. def __getattr__(self, name):
  113. if name == '__members__':
  114. return dir(self._get_current_object())
  115. return getattr(self._get_current_object(), name)
  116. def __setitem__(self, key, value):
  117. self._get_current_object()[key] = value
  118. def __delitem__(self, key):
  119. del self._get_current_object()[key]
  120. def __setslice__(self, i, j, seq):
  121. self._get_current_object()[i:j] = seq
  122. def __delslice__(self, i, j):
  123. del self._get_current_object()[i:j]
  124. def __setattr__(self, name, value):
  125. setattr(self._get_current_object(), name, value)
  126. def __delattr__(self, name):
  127. delattr(self._get_current_object(), name)
  128. def __str__(self):
  129. return str(self._get_current_object())
  130. def __lt__(self, other):
  131. return self._get_current_object() < other
  132. def __le__(self, other):
  133. return self._get_current_object() <= other
  134. def __eq__(self, other):
  135. return self._get_current_object() == other
  136. def __ne__(self, other):
  137. return self._get_current_object() != other
  138. def __gt__(self, other):
  139. return self._get_current_object() > other
  140. def __ge__(self, other):
  141. return self._get_current_object() >= other
  142. def __hash__(self):
  143. return hash(self._get_current_object())
  144. def __call__(self, *a, **kw):
  145. return self._get_current_object()(*a, **kw)
  146. def __len__(self):
  147. return len(self._get_current_object())
  148. def __getitem__(self, i):
  149. return self._get_current_object()[i]
  150. def __iter__(self):
  151. return iter(self._get_current_object())
  152. def __contains__(self, i):
  153. return i in self._get_current_object()
  154. def __getslice__(self, i, j):
  155. return self._get_current_object()[i:j]
  156. def __add__(self, other):
  157. return self._get_current_object() + other
  158. def __sub__(self, other):
  159. return self._get_current_object() - other
  160. def __mul__(self, other):
  161. return self._get_current_object() * other
  162. def __floordiv__(self, other):
  163. return self._get_current_object() // other
  164. def __mod__(self, other):
  165. return self._get_current_object() % other
  166. def __divmod__(self, other):
  167. return self._get_current_object().__divmod__(other)
  168. def __pow__(self, other):
  169. return self._get_current_object() ** other
  170. def __lshift__(self, other):
  171. return self._get_current_object() << other
  172. def __rshift__(self, other):
  173. return self._get_current_object() >> other
  174. def __and__(self, other):
  175. return self._get_current_object() & other
  176. def __xor__(self, other):
  177. return self._get_current_object() ^ other
  178. def __or__(self, other):
  179. return self._get_current_object() | other
  180. def __div__(self, other):
  181. return self._get_current_object().__div__(other)
  182. def __truediv__(self, other):
  183. return self._get_current_object().__truediv__(other)
  184. def __neg__(self):
  185. return -(self._get_current_object())
  186. def __pos__(self):
  187. return +(self._get_current_object())
  188. def __abs__(self):
  189. return abs(self._get_current_object())
  190. def __invert__(self):
  191. return ~(self._get_current_object())
  192. def __complex__(self):
  193. return complex(self._get_current_object())
  194. def __int__(self):
  195. return int(self._get_current_object())
  196. def __float__(self):
  197. return float(self._get_current_object())
  198. def __oct__(self):
  199. return oct(self._get_current_object())
  200. def __hex__(self):
  201. return hex(self._get_current_object())
  202. def __index__(self):
  203. return self._get_current_object().__index__()
  204. def __coerce__(self, other):
  205. return self._get_current_object().__coerce__(other)
  206. def __enter__(self):
  207. return self._get_current_object().__enter__()
  208. def __exit__(self, *a, **kw):
  209. return self._get_current_object().__exit__(*a, **kw)
  210. def __reduce__(self):
  211. return self._get_current_object().__reduce__()
  212. if not PY3: # pragma: no cover
  213. def __cmp__(self, other):
  214. return cmp(self._get_current_object(), other) # noqa
  215. def __long__(self):
  216. return long(self._get_current_object()) # noqa
  217. def __unicode__(self):
  218. try:
  219. return string(self._get_current_object())
  220. except RuntimeError: # pragma: no cover
  221. return repr(self)
  222. class PromiseProxy(Proxy):
  223. """Proxy that evaluates object once.
  224. :class:`Proxy` will evaluate the object each time, while the
  225. promise will only evaluate it once.
  226. """
  227. __slots__ = ('__pending__', '__weakref__')
  228. def _get_current_object(self):
  229. try:
  230. return object.__getattribute__(self, '__thing')
  231. except AttributeError:
  232. return self.__evaluate__()
  233. def __then__(self, fun, *args, **kwargs):
  234. if self.__evaluated__():
  235. return fun(*args, **kwargs)
  236. from collections import deque
  237. try:
  238. pending = object.__getattribute__(self, '__pending__')
  239. except AttributeError:
  240. pending = None
  241. if pending is None:
  242. pending = deque()
  243. object.__setattr__(self, '__pending__', pending)
  244. pending.append((fun, args, kwargs))
  245. def __evaluated__(self):
  246. try:
  247. object.__getattribute__(self, '__thing')
  248. except AttributeError:
  249. return False
  250. return True
  251. def __maybe_evaluate__(self):
  252. return self._get_current_object()
  253. def __evaluate__(self,
  254. _clean=('_Proxy__local',
  255. '_Proxy__args',
  256. '_Proxy__kwargs')):
  257. try:
  258. thing = Proxy._get_current_object(self)
  259. except Exception:
  260. raise
  261. else:
  262. object.__setattr__(self, '__thing', thing)
  263. for attr in _clean:
  264. try:
  265. object.__delattr__(self, attr)
  266. except AttributeError: # pragma: no cover
  267. # May mask errors so ignore
  268. pass
  269. try:
  270. pending = object.__getattribute__(self, '__pending__')
  271. except AttributeError:
  272. pass
  273. else:
  274. try:
  275. while pending:
  276. fun, args, kwargs = pending.popleft()
  277. fun(*args, **kwargs)
  278. finally:
  279. try:
  280. object.__delattr__(self, '__pending__')
  281. except AttributeError: # pragma: no cover
  282. pass
  283. return thing
  284. def maybe_evaluate(obj):
  285. """Attempt to evaluate promise, even if obj is not a promise."""
  286. try:
  287. return obj.__maybe_evaluate__()
  288. except AttributeError:
  289. return obj
  290. # ############# Module Generation ##########################
  291. # Utilities to dynamically
  292. # recreate modules, either for lazy loading or
  293. # to create old modules at runtime instead of
  294. # having them litter the source tree.
  295. # import fails in python 2.5. fallback to reduce in stdlib
  296. MODULE_DEPRECATED = """
  297. The module %s is deprecated and will be removed in a future version.
  298. """
  299. DEFAULT_ATTRS = {'__file__', '__path__', '__doc__', '__all__'}
  300. # im_func is no longer available in Py3.
  301. # instead the unbound method itself can be used.
  302. if sys.version_info[0] == 3: # pragma: no cover
  303. def fun_of_method(method):
  304. return method
  305. else:
  306. def fun_of_method(method): # noqa
  307. return method.im_func
  308. def getappattr(path):
  309. """Get attribute from current_app recursively.
  310. Example: ``getappattr('amqp.get_task_consumer')``.
  311. """
  312. from celery import current_app
  313. return current_app._rgetattr(path)
  314. def _compat_periodic_task_decorator(*args, **kwargs):
  315. from celery.task import periodic_task
  316. return periodic_task(*args, **kwargs)
  317. COMPAT_MODULES = {
  318. 'celery': {
  319. 'execute': {
  320. 'send_task': 'send_task',
  321. },
  322. 'decorators': {
  323. 'task': 'task',
  324. 'periodic_task': _compat_periodic_task_decorator,
  325. },
  326. 'log': {
  327. 'get_default_logger': 'log.get_default_logger',
  328. 'setup_logger': 'log.setup_logger',
  329. 'setup_logging_subsystem': 'log.setup_logging_subsystem',
  330. 'redirect_stdouts_to_logger': 'log.redirect_stdouts_to_logger',
  331. },
  332. 'messaging': {
  333. 'TaskConsumer': 'amqp.TaskConsumer',
  334. 'establish_connection': 'connection',
  335. 'get_consumer_set': 'amqp.TaskConsumer',
  336. },
  337. 'registry': {
  338. 'tasks': 'tasks',
  339. },
  340. },
  341. 'celery.task': {
  342. 'control': {
  343. 'broadcast': 'control.broadcast',
  344. 'rate_limit': 'control.rate_limit',
  345. 'time_limit': 'control.time_limit',
  346. 'ping': 'control.ping',
  347. 'revoke': 'control.revoke',
  348. 'discard_all': 'control.purge',
  349. 'inspect': 'control.inspect',
  350. },
  351. 'schedules': 'celery.schedules',
  352. 'chords': 'celery.canvas',
  353. }
  354. }
  355. #: We exclude these from dir(celery)
  356. DEPRECATED_ATTRS = set(COMPAT_MODULES['celery'].keys()) | {'subtask'}
  357. class class_property(object):
  358. def __init__(self, getter=None, setter=None):
  359. if getter is not None and not isinstance(getter, classmethod):
  360. getter = classmethod(getter)
  361. if setter is not None and not isinstance(setter, classmethod):
  362. setter = classmethod(setter)
  363. self.__get = getter
  364. self.__set = setter
  365. info = getter.__get__(object) # just need the info attrs.
  366. self.__doc__ = info.__doc__
  367. self.__name__ = info.__name__
  368. self.__module__ = info.__module__
  369. def __get__(self, obj, type=None):
  370. if obj and type is None:
  371. type = obj.__class__
  372. return self.__get.__get__(obj, type)()
  373. def __set__(self, obj, value):
  374. if obj is None:
  375. return self
  376. return self.__set.__get__(obj)(value)
  377. def setter(self, setter):
  378. return self.__class__(self.__get, setter)
  379. def reclassmethod(method):
  380. return classmethod(fun_of_method(method))
  381. class LazyModule(ModuleType):
  382. _compat_modules = ()
  383. _all_by_module = {}
  384. _direct = {}
  385. _object_origins = {}
  386. def __getattr__(self, name):
  387. if name in self._object_origins:
  388. module = __import__(self._object_origins[name], None, None, [name])
  389. for item in self._all_by_module[module.__name__]:
  390. setattr(self, item, getattr(module, item))
  391. return getattr(module, name)
  392. elif name in self._direct: # pragma: no cover
  393. module = __import__(self._direct[name], None, None, [name])
  394. setattr(self, name, module)
  395. return module
  396. return ModuleType.__getattribute__(self, name)
  397. def __dir__(self):
  398. return [
  399. attr for attr in set(self.__all__) | DEFAULT_ATTRS
  400. if attr not in DEPRECATED_ATTRS
  401. ]
  402. def __reduce__(self):
  403. return import_module, (self.__name__,)
  404. def create_module(name, attrs, cls_attrs=None, pkg=None,
  405. base=LazyModule, prepare_attr=None):
  406. fqdn = '.'.join([pkg.__name__, name]) if pkg else name
  407. cls_attrs = {} if cls_attrs is None else cls_attrs
  408. pkg, _, modname = name.rpartition('.')
  409. cls_attrs['__module__'] = pkg
  410. attrs = {
  411. attr_name: (prepare_attr(attr) if prepare_attr else attr)
  412. for attr_name, attr in items(attrs)
  413. }
  414. module = sys.modules[fqdn] = type(
  415. bytes_if_py2(modname), (base,), cls_attrs)(bytes_if_py2(name))
  416. module.__dict__.update(attrs)
  417. return module
  418. def recreate_module(name, compat_modules=(), by_module={}, direct={},
  419. base=LazyModule, **attrs):
  420. old_module = sys.modules[name]
  421. origins = get_origins(by_module)
  422. compat_modules = COMPAT_MODULES.get(name, ())
  423. _all = tuple(set(reduce(
  424. operator.add,
  425. [tuple(v) for v in [compat_modules, origins, direct, attrs]],
  426. )))
  427. if sys.version_info[0] < 3:
  428. _all = [s.encode() for s in _all]
  429. cattrs = {
  430. '_compat_modules': compat_modules,
  431. '_all_by_module': by_module, '_direct': direct,
  432. '_object_origins': origins,
  433. '__all__': _all,
  434. }
  435. new_module = create_module(name, attrs, cls_attrs=cattrs, base=base)
  436. new_module.__dict__.update({
  437. mod: get_compat_module(new_module, mod) for mod in compat_modules
  438. })
  439. return old_module, new_module
  440. def get_compat_module(pkg, name):
  441. def prepare(attr):
  442. if isinstance(attr, string_t):
  443. return Proxy(getappattr, (attr,))
  444. return attr
  445. attrs = COMPAT_MODULES[pkg.__name__][name]
  446. if isinstance(attrs, string_t):
  447. fqdn = '.'.join([pkg.__name__, name])
  448. module = sys.modules[fqdn] = import_module(attrs)
  449. return module
  450. attrs[bytes_if_py2('__all__')] = list(attrs)
  451. return create_module(name, dict(attrs), pkg=pkg, prepare_attr=prepare)
  452. def get_origins(defs):
  453. origins = {}
  454. for module, attrs in items(defs):
  455. origins.update({attr: module for attr in attrs})
  456. return origins