attachment_file.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import pathlib
  2. import aiofiles
  3. from .aleatory_file_name import aleatory_file_name
  4. class attachment_file:
  5. def __init__(
  6. self,
  7. extension: str,
  8. root: pathlib.Path
  9. ) -> None:
  10. self.__root = root
  11. self.__name = self.__get_name(extension)
  12. async def load(self) -> bytes:
  13. async with aiofiles.open(self.path, "rb") as handler:
  14. return await handler.read()
  15. async def store(self, content: bytes) -> object:
  16. async with aiofiles.open(self.path, "wb") as handler:
  17. await handler.write(content)
  18. return self
  19. def __get_name(self, extension: str) -> str:
  20. while True:
  21. new_name = aleatory_file_name(extension)
  22. new_path = self.root / pathlib.Path(new_name)
  23. if not new_path.is_file() and not new_path.exists():
  24. return new_name
  25. def exists(self) -> bool:
  26. return self.path.exists() and self.path.is_file()
  27. @property
  28. def name(self) -> str:
  29. return self.__name
  30. @property
  31. def root(self) -> pathlib.Path:
  32. return self.__root
  33. @property
  34. def path(self) -> pathlib.Path:
  35. return self.root / pathlib.Path(self.name)