five.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.five
  4. ~~~~~~~~~~~
  5. Compatibility implementations of features
  6. only available in newer Python versions.
  7. """
  8. from __future__ import absolute_import
  9. try:
  10. from collections import Counter
  11. except ImportError: # pragma: no cover
  12. from collections import defaultdict
  13. def Counter():
  14. return defaultdict(int)
  15. ############## py3k #########################################################
  16. import sys
  17. PY3 = sys.version_info[0] == 3
  18. try:
  19. reload = reload # noqa
  20. except NameError: # pragma: no cover
  21. from imp import reload # noqa
  22. try:
  23. from UserList import UserList # noqa
  24. except ImportError: # pragma: no cover
  25. from collections import UserList # noqa
  26. try:
  27. from UserDict import UserDict # noqa
  28. except ImportError: # pragma: no cover
  29. from collections import UserDict # noqa
  30. if PY3: # pragma: no cover
  31. import builtins
  32. from queue import Queue, Empty
  33. from itertools import zip_longest
  34. from io import StringIO, BytesIO
  35. map = map
  36. string = str
  37. string_t = str
  38. long_t = int
  39. text_t = str
  40. range = range
  41. int_types = (int, )
  42. open_fqdn = 'builtins.open'
  43. def items(d):
  44. return d.items()
  45. def keys(d):
  46. return d.keys()
  47. def values(d):
  48. return d.values()
  49. def nextfun(it):
  50. return it.__next__
  51. exec_ = getattr(builtins, 'exec')
  52. def reraise(tp, value, tb=None):
  53. if value.__traceback__ is not tb:
  54. raise value.with_traceback(tb)
  55. raise value
  56. class WhateverIO(StringIO):
  57. def write(self, data):
  58. if isinstance(data, bytes):
  59. data = data.encode()
  60. StringIO.write(self, data)
  61. else:
  62. import __builtin__ as builtins # noqa
  63. from Queue import Queue, Empty # noqa
  64. from itertools import imap as map, izip_longest as zip_longest # noqa
  65. from StringIO import StringIO # noqa
  66. string = unicode # noqa
  67. string_t = basestring # noqa
  68. text_t = unicode
  69. long_t = long # noqa
  70. range = xrange
  71. int_types = (int, long)
  72. open_fqdn = '__builtin__.open'
  73. def items(d): # noqa
  74. return d.iteritems()
  75. def keys(d): # noqa
  76. return d.iterkeys()
  77. def values(d): # noqa
  78. return d.itervalues()
  79. def nextfun(it): # noqa
  80. return it.next
  81. def exec_(code, globs=None, locs=None): # pragma: no cover
  82. """Execute code in a namespace."""
  83. if globs is None:
  84. frame = sys._getframe(1)
  85. globs = frame.f_globals
  86. if locs is None:
  87. locs = frame.f_locals
  88. del frame
  89. elif locs is None:
  90. locs = globs
  91. exec("""exec code in globs, locs""")
  92. exec_("""def reraise(tp, value, tb=None): raise tp, value, tb""")
  93. BytesIO = WhateverIO = StringIO # noqa
  94. def with_metaclass(Type, skip_attrs=set(['__dict__', '__weakref__'])):
  95. """Class decorator to set metaclass.
  96. Works with both Python 3 and Python 3 and it does not add
  97. an extra class in the lookup order like ``six.with_metaclass`` does
  98. (that is -- it copies the original class instead of using inheritance).
  99. """
  100. def _clone_with_metaclass(Class):
  101. attrs = dict((key, value) for key, value in items(vars(Class))
  102. if key not in skip_attrs)
  103. return Type(Class.__name__, Class.__bases__, attrs)
  104. return _clone_with_metaclass
  105. ############## collections.OrderedDict ######################################
  106. # was moved to kombu
  107. from kombu.utils.compat import OrderedDict # noqa
  108. ############## threading.TIMEOUT_MAX #######################################
  109. try:
  110. from threading import TIMEOUT_MAX as THREAD_TIMEOUT_MAX
  111. except ImportError:
  112. THREAD_TIMEOUT_MAX = 1e10 # noqa
  113. ############## format(int, ',d') ##########################
  114. if sys.version_info >= (2, 7): # pragma: no cover
  115. def format_d(i):
  116. return format(i, ',d')
  117. else: # pragma: no cover
  118. def format_d(i): # noqa
  119. s = '%d' % i
  120. groups = []
  121. while s and s[-1].isdigit():
  122. groups.append(s[-3:])
  123. s = s[:-3]
  124. return s + ','.join(reversed(groups))
  125. ############## Module Generation ##########################
  126. # Utilities to dynamically
  127. # recreate modules, either for lazy loading or
  128. # to create old modules at runtime instead of
  129. # having them litter the source tree.
  130. import operator
  131. import sys
  132. from functools import reduce
  133. from importlib import import_module
  134. from types import ModuleType
  135. MODULE_DEPRECATED = """
  136. The module %s is deprecated and will be removed in a future version.
  137. """
  138. DEFAULT_ATTRS = set(['__file__', '__path__', '__doc__', '__all__'])
  139. # im_func is no longer available in Py3.
  140. # instead the unbound method itself can be used.
  141. if sys.version_info[0] == 3: # pragma: no cover
  142. def fun_of_method(method):
  143. return method
  144. else:
  145. def fun_of_method(method): # noqa
  146. return method.im_func
  147. def getappattr(path):
  148. """Gets attribute from the current_app recursively,
  149. e.g. getappattr('amqp.get_task_consumer')``."""
  150. from celery import current_app
  151. return current_app._rgetattr(path)
  152. def _compat_task_decorator(*args, **kwargs):
  153. from celery import current_app
  154. kwargs.setdefault('accept_magic_kwargs', True)
  155. return current_app.task(*args, **kwargs)
  156. def _compat_periodic_task_decorator(*args, **kwargs):
  157. from celery.task import periodic_task
  158. kwargs.setdefault('accept_magic_kwargs', True)
  159. return periodic_task(*args, **kwargs)
  160. COMPAT_MODULES = {
  161. 'celery': {
  162. 'execute': {
  163. 'send_task': 'send_task',
  164. },
  165. 'decorators': {
  166. 'task': _compat_task_decorator,
  167. 'periodic_task': _compat_periodic_task_decorator,
  168. },
  169. 'log': {
  170. 'get_default_logger': 'log.get_default_logger',
  171. 'setup_logger': 'log.setup_logger',
  172. 'setup_loggig_subsystem': 'log.setup_logging_subsystem',
  173. 'redirect_stdouts_to_logger': 'log.redirect_stdouts_to_logger',
  174. },
  175. 'messaging': {
  176. 'TaskPublisher': 'amqp.TaskPublisher',
  177. 'TaskConsumer': 'amqp.TaskConsumer',
  178. 'establish_connection': 'connection',
  179. 'with_connection': 'with_default_connection',
  180. 'get_consumer_set': 'amqp.TaskConsumer',
  181. },
  182. 'registry': {
  183. 'tasks': 'tasks',
  184. },
  185. },
  186. 'celery.task': {
  187. 'control': {
  188. 'broadcast': 'control.broadcast',
  189. 'rate_limit': 'control.rate_limit',
  190. 'time_limit': 'control.time_limit',
  191. 'ping': 'control.ping',
  192. 'revoke': 'control.revoke',
  193. 'discard_all': 'control.purge',
  194. 'inspect': 'control.inspect',
  195. },
  196. 'schedules': 'celery.schedules',
  197. 'chords': 'celery.canvas',
  198. }
  199. }
  200. class class_property(object):
  201. def __init__(self, fget=None, fset=None):
  202. assert fget and isinstance(fget, classmethod)
  203. assert isinstance(fset, classmethod) if fset else True
  204. self.__get = fget
  205. self.__set = fset
  206. info = fget.__get__(object) # just need the info attrs.
  207. self.__doc__ = info.__doc__
  208. self.__name__ = info.__name__
  209. self.__module__ = info.__module__
  210. def __get__(self, obj, type=None):
  211. if obj and type is None:
  212. type = obj.__class__
  213. return self.__get.__get__(obj, type)()
  214. def __set__(self, obj, value):
  215. if obj is None:
  216. return self
  217. return self.__set.__get__(obj)(value)
  218. def reclassmethod(method):
  219. return classmethod(fun_of_method(method))
  220. class MagicModule(ModuleType):
  221. _compat_modules = ()
  222. _all_by_module = {}
  223. _direct = {}
  224. _object_origins = {}
  225. def __getattr__(self, name):
  226. if name in self._object_origins:
  227. module = __import__(self._object_origins[name], None, None, [name])
  228. for item in self._all_by_module[module.__name__]:
  229. setattr(self, item, getattr(module, item))
  230. return getattr(module, name)
  231. elif name in self._direct: # pragma: no cover
  232. module = __import__(self._direct[name], None, None, [name])
  233. setattr(self, name, module)
  234. return module
  235. return ModuleType.__getattribute__(self, name)
  236. def __dir__(self):
  237. return list(set(self.__all__) | DEFAULT_ATTRS)
  238. def create_module(name, attrs, cls_attrs=None, pkg=None,
  239. base=MagicModule, prepare_attr=None):
  240. fqdn = '.'.join([pkg.__name__, name]) if pkg else name
  241. cls_attrs = {} if cls_attrs is None else cls_attrs
  242. attrs = dict((attr_name, prepare_attr(attr) if prepare_attr else attr)
  243. for attr_name, attr in items(attrs))
  244. module = sys.modules[fqdn] = type(name, (base, ), cls_attrs)(fqdn)
  245. module.__dict__.update(attrs)
  246. return module
  247. def recreate_module(name, compat_modules=(), by_module={}, direct={},
  248. base=MagicModule, **attrs):
  249. old_module = sys.modules[name]
  250. origins = get_origins(by_module)
  251. compat_modules = COMPAT_MODULES.get(name, ())
  252. cattrs = dict(
  253. _compat_modules=compat_modules,
  254. _all_by_module=by_module, _direct=direct,
  255. _object_origins=origins,
  256. __all__=tuple(set(reduce(
  257. operator.add,
  258. [tuple(v) for v in [compat_modules, origins, direct, attrs]],
  259. ))),
  260. )
  261. new_module = create_module(name, attrs, cls_attrs=cattrs, base=base)
  262. new_module.__dict__.update(dict((mod, get_compat_module(new_module, mod))
  263. for mod in compat_modules))
  264. return old_module, new_module
  265. def get_compat_module(pkg, name):
  266. from .local import Proxy
  267. def prepare(attr):
  268. if isinstance(attr, string_t):
  269. return Proxy(getappattr, (attr, ))
  270. return attr
  271. attrs = COMPAT_MODULES[pkg.__name__][name]
  272. if isinstance(attrs, string_t):
  273. fqdn = '.'.join([pkg.__name__, name])
  274. module = sys.modules[fqdn] = import_module(attrs)
  275. return module
  276. attrs['__all__'] = list(attrs)
  277. return create_module(name, dict(attrs), pkg=pkg, prepare_attr=prepare)
  278. def get_origins(defs):
  279. origins = {}
  280. for module, attrs in items(defs):
  281. origins.update(dict((attr, module) for attr in attrs))
  282. return origins