utils.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. """Compatibility utilities."""
  2. from __future__ import absolute_import, unicode_literals
  3. import logging
  4. # enables celery 3.1.23 to start again
  5. from vine import promise # noqa
  6. from vine.utils import wraps
  7. from .five import PY3, string_t, text_t
  8. try:
  9. import fcntl
  10. except ImportError: # pragma: no cover
  11. fcntl = None # noqa
  12. try:
  13. from os import set_cloexec # Python 3.4?
  14. except ImportError: # pragma: no cover
  15. def set_cloexec(fd, cloexec): # noqa
  16. """Set flag to close fd after exec."""
  17. if fcntl is None:
  18. return
  19. try:
  20. FD_CLOEXEC = fcntl.FD_CLOEXEC
  21. except AttributeError:
  22. raise NotImplementedError(
  23. 'close-on-exec flag not supported on this platform',
  24. )
  25. flags = fcntl.fcntl(fd, fcntl.F_GETFD)
  26. if cloexec:
  27. flags |= FD_CLOEXEC
  28. else:
  29. flags &= ~FD_CLOEXEC
  30. return fcntl.fcntl(fd, fcntl.F_SETFD, flags)
  31. def get_errno(exc):
  32. """Get exception errno (if set).
  33. Notes:
  34. :exc:`socket.error` and :exc:`IOError` first got
  35. the ``.errno`` attribute in Py2.7.
  36. """
  37. try:
  38. return exc.errno
  39. except AttributeError:
  40. try:
  41. # e.args = (errno, reason)
  42. if isinstance(exc.args, tuple) and len(exc.args) == 2:
  43. return exc.args[0]
  44. except AttributeError:
  45. pass
  46. return 0
  47. def coro(gen):
  48. """Decorator to mark generator as a co-routine."""
  49. @wraps(gen)
  50. def _boot(*args, **kwargs):
  51. co = gen(*args, **kwargs)
  52. next(co)
  53. return co
  54. return _boot
  55. if PY3: # pragma: no cover
  56. def str_to_bytes(s):
  57. """Convert str to bytes."""
  58. if isinstance(s, str):
  59. return s.encode('utf-8', 'surrogatepass')
  60. return s
  61. def bytes_to_str(s):
  62. """Convert bytes to str."""
  63. if isinstance(s, bytes):
  64. return s.decode('utf-8', 'surrogatepass')
  65. return s
  66. else:
  67. def str_to_bytes(s): # noqa
  68. """Convert str to bytes."""
  69. if isinstance(s, text_t):
  70. return s.encode('utf-8')
  71. return s
  72. def bytes_to_str(s): # noqa
  73. """Convert bytes to str."""
  74. return s
  75. class NullHandler(logging.Handler):
  76. """A logging handler that does nothing."""
  77. def emit(self, record):
  78. pass
  79. def get_logger(logger):
  80. """Get logger by name."""
  81. if isinstance(logger, string_t):
  82. logger = logging.getLogger(logger)
  83. if not logger.handlers:
  84. logger.addHandler(NullHandler())
  85. return logger