users_saver.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import json
  2. import pathlib
  3. from .user import user
  4. from .user import user_factory
  5. from .user import user_builder
  6. from .exception import config_exception
  7. from .users_collection import users_collection
  8. class users_saver:
  9. """
  10. This class is responsible for saving and storing user config file.
  11. """
  12. def __init__(self, collection: users_collection) -> None:
  13. """
  14. This initialize class, by set users collection.
  15. Parameters:
  16. collection (users_collection): This is collection of users to save
  17. """
  18. self.__collection = collection
  19. self.__where = None
  20. @property
  21. def users(self) -> list:
  22. """ This return list of users in setup collection. """
  23. return [ count.flat for count in self.__collection.all ]
  24. def drop(self, where: pathlib.Path) -> object:
  25. """
  26. This drop config file, when it already exists. If given path is
  27. directory, raise config exception. Path is been saving to use it
  28. in save. When first call to drop, save after it could be call without
  29. parameters.
  30. Parameters:
  31. where (pathlib.Path): Place where config file had been
  32. Returns:
  33. (users_saver): Object instance itself
  34. """
  35. self.__where = where
  36. if not where.exists():
  37. return self
  38. if where.is_dir():
  39. content = "Can not remove users config, because target \""
  40. content = content + str(where) + "\" is file."
  41. raise config_exception(content)
  42. where.unlink()
  43. return self
  44. def save(self, where: pathlib.Path | None = None) -> object:
  45. """
  46. This function save users collection as users config file. When place
  47. is not provided, trying to load it from previous place, in drop. When
  48. config file already exists, raise config.
  49. Parameters:
  50. where (pathlib.Path | None): Place to save config (default: None)
  51. Returns:
  52. (users_saver): Instance of this class itself
  53. """
  54. if where is None:
  55. where = self.__where
  56. if where is None:
  57. raise RuntimeError("Where is not set.")
  58. if where.exists():
  59. content = "Config file \"" + str(where) + "\" already exists."
  60. raise config_exception(content)
  61. with where.open("w") as handle:
  62. handle.write(json.dumps(self.users))
  63. return self