attachments_manager.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import tortoise.transactions
  2. from .container_blob import encoded
  3. from .attachment import attachment
  4. from .attachment import attachment_proxy
  5. from .attachments_directory import attachments_directory
  6. from .exceptions import id_is_invalid
  7. from .exceptions import not_found
  8. from .validators import validators
  9. class attachments_manager:
  10. def __init__(self, directory: attachments_directory) -> None:
  11. self.__directory = directory
  12. @property
  13. def directory(self) -> attachments_directory:
  14. return self.__directory
  15. async def get_all(self) -> tuple:
  16. items = await attachment.all()
  17. return tuple(items)
  18. async def upload(
  19. self,
  20. content: str,
  21. extension: str,
  22. name: str,
  23. description: str
  24. ) -> int:
  25. decoded = await encoded(content).decode()
  26. decoded = decoded.result()
  27. proxy = await self.directory.store(decoded, extension)
  28. proxy.set_name(name)
  29. proxy.set_description(description)
  30. created = proxy.result()
  31. async with tortoise.transactions.in_transaction():
  32. await created.save()
  33. return created.get_identifier()
  34. async def edit(
  35. self,
  36. id: int,
  37. name: str,
  38. description: str
  39. ) -> int:
  40. async with tortoise.transactions.in_transaction():
  41. target = await self.require_by_id(id)
  42. proxy = attachment_proxy(target)
  43. proxy.set_name(name)
  44. proxy.set_description(description)
  45. result = proxy.result()
  46. await result.save()
  47. return result.get_identifier()
  48. async def remove(self, id: int) -> None:
  49. target = await self.require_by_id(id)
  50. items = await target.get_related("item", "attachments")
  51. await target.delete()
  52. async def get_by_id(self, id: int) -> attachment | None:
  53. if validators.id(id) is False:
  54. raise id_is_invalid(id)
  55. async with tortoise.transactions.in_transaction():
  56. return await attachment.filter(id = id).first()
  57. async def require_by_id(self, id: int) -> attachment:
  58. result = await self.get_by_id(id)
  59. if result is None:
  60. raise not_found("attachment", id = id)
  61. return result