utils.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import functools
  2. def delegate_to_executor(*attrs):
  3. def cls_builder(cls):
  4. for attr_name in attrs:
  5. setattr(cls, attr_name, _make_delegate_method(attr_name))
  6. return cls
  7. return cls_builder
  8. def proxy_method_directly(*attrs):
  9. def cls_builder(cls):
  10. for attr_name in attrs:
  11. setattr(cls, attr_name, _make_proxy_method(attr_name))
  12. return cls
  13. return cls_builder
  14. def proxy_property_directly(*attrs):
  15. def cls_builder(cls):
  16. for attr_name in attrs:
  17. setattr(cls, attr_name, _make_proxy_property(attr_name))
  18. return cls
  19. return cls_builder
  20. def cond_delegate_to_executor(*attrs):
  21. def cls_builder(cls):
  22. for attr_name in attrs:
  23. setattr(cls, attr_name, _make_cond_delegate_method(attr_name))
  24. return cls
  25. return cls_builder
  26. def _make_delegate_method(attr_name):
  27. async def method(self, *args, **kwargs):
  28. cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs)
  29. return await self._loop.run_in_executor(self._executor, cb)
  30. return method
  31. def _make_proxy_method(attr_name):
  32. def method(self, *args, **kwargs):
  33. return getattr(self._file, attr_name)(*args, **kwargs)
  34. return method
  35. def _make_proxy_property(attr_name):
  36. def proxy_property(self):
  37. return getattr(self._file, attr_name)
  38. return property(proxy_property)
  39. def _make_cond_delegate_method(attr_name):
  40. """For spooled temp files, delegate only if rolled to file object"""
  41. async def method(self, *args, **kwargs):
  42. if self._file._rolled:
  43. cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs)
  44. return await self._loop.run_in_executor(self._executor, cb)
  45. else:
  46. return getattr(self._file, attr_name)(*args, **kwargs)
  47. return method