five.py 11 KB

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