five.py 11 KB

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