local.py 17 KB

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