attachment_file.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import pathlib
  2. import aiofiles
  3. from .attachment import attachment
  4. from .attachment import attachment_proxy
  5. from .aleatory_file_name import aleatory_file_name
  6. class attachment_file:
  7. @classmethod
  8. def create(cls, directory: pathlib.Path, extension: str) -> object:
  9. while True:
  10. new_name = aleatory_file_name.path(extension)
  11. new_path = directory / new_name
  12. if not new_path.exists() and not new_path.is_file():
  13. return cls(new_name, directory)
  14. def __init__(
  15. self,
  16. file_name: pathlib.Path,
  17. directory: pathlib.Path
  18. ) -> None:
  19. self.__file_name = file_name
  20. self.__directory = directory
  21. self.__file_path = directory / file_name
  22. @property
  23. def path(self) -> pathlib.Path:
  24. return self.__file_path
  25. @property
  26. def directory(self) -> pathlib.Path:
  27. return self.__directory
  28. @property
  29. def name(self) -> str:
  30. return str(self.__file_name)
  31. @property
  32. def relative_path(self) -> pathlib.Path:
  33. return self.__file_name
  34. async def store(self, content: bytes) -> attachment_proxy:
  35. async with aiofiles.open(self.path, "wb") as handler:
  36. await handler.write(content)
  37. return attachment_proxy.create(self.name)
  38. async def load(self) -> bytes:
  39. async with aiofiles.open(self.path, "rb") as handler:
  40. return await handler.read()