five.py 11 KB

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