serialization.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. from celery.utils.functional import curry
  2. import operator
  3. try:
  4. import cPickle as pickle
  5. except ImportError:
  6. import pickle
  7. def find_nearest_pickleable_exception(exc):
  8. """With an exception instance, iterate over its super classes (by mro)
  9. and find the first super exception that is pickleable. It does
  10. not go below :exc:`Exception` (i.e. it skips :exc:`Exception`,
  11. :class:`BaseException` and :class:`object`). If that happens
  12. you should use :exc:`UnpickleableException` instead.
  13. :param exc: An exception instance.
  14. :returns: the nearest exception if it's not :exc:`Exception` or below,
  15. if it is it returns ``None``.
  16. :rtype: :exc:`Exception`
  17. """
  18. unwanted = (Exception, BaseException, object)
  19. is_unwanted = lambda exc: any(map(curry(operator.is_, exc), unwanted))
  20. mro_ = getattr(exc.__class__, "mro", lambda: [])
  21. for supercls in mro_():
  22. if is_unwanted(supercls):
  23. # only BaseException and object, from here on down,
  24. # we don't care about these.
  25. return None
  26. try:
  27. exc_args = getattr(exc, "args", [])
  28. superexc = supercls(*exc_args)
  29. pickle.dumps(superexc)
  30. except:
  31. pass
  32. else:
  33. return superexc
  34. return None
  35. def create_exception_cls(name, module, parent=None):
  36. """Dynamically create an exception class."""
  37. if not parent:
  38. parent = Exception
  39. return type(name, (parent, ), {"__module__": module})
  40. class UnpickleableExceptionWrapper(Exception):
  41. """Wraps unpickleable exceptions.
  42. :param exc_module: see :attr:`exc_module`.
  43. :param exc_cls_name: see :attr:`exc_cls_name`.
  44. :param exc_args: see :attr:`exc_args`
  45. .. attribute:: exc_module
  46. The module of the original exception.
  47. .. attribute:: exc_cls_name
  48. The name of the original exception class.
  49. .. attribute:: exc_args
  50. The arguments for the original exception.
  51. Example
  52. >>> try:
  53. ... something_raising_unpickleable_exc()
  54. >>> except Exception, e:
  55. ... exc = UnpickleableException(e.__class__.__module__,
  56. ... e.__class__.__name__,
  57. ... e.args)
  58. ... pickle.dumps(exc) # Works fine.
  59. """
  60. def __init__(self, exc_module, exc_cls_name, exc_args):
  61. self.exc_module = exc_module
  62. self.exc_cls_name = exc_cls_name
  63. self.exc_args = exc_args
  64. super(Exception, self).__init__(exc_module, exc_cls_name, exc_args)
  65. def get_pickleable_exception(exc):
  66. """Make sure exception is pickleable."""
  67. nearest = find_nearest_pickleable_exception(exc)
  68. if nearest:
  69. return nearest
  70. try:
  71. pickle.dumps(exc)
  72. except pickle.PickleError:
  73. excwrapper = UnpickleableExceptionWrapper(
  74. exc.__class__.__module__,
  75. exc.__class__.__name__,
  76. getattr(exc, "args", []))
  77. return excwrapper
  78. return exc
  79. def get_pickled_exception(exc):
  80. """Get original exception from exception pickled using
  81. :meth:`get_pickleable_exception`."""
  82. if isinstance(exc, UnpickleableExceptionWrapper):
  83. exc_cls = create_exception_cls(exc.exc_cls_name,
  84. exc.exc_module)
  85. return exc_cls(*exc.exc_args)
  86. return exc