utils.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. from functools import lru_cache
  5. from apps.setting.models import Setting, KEYS_DEFAULT
  6. from libs.ssh import SSH
  7. import json
  8. class AppSetting:
  9. @classmethod
  10. @lru_cache(maxsize=64)
  11. def get(cls, key):
  12. info = Setting.objects.filter(key=key).first()
  13. if not info:
  14. raise KeyError(f'no such key for {key!r}')
  15. return info.real_val
  16. @classmethod
  17. def get_default(cls, key, default=None):
  18. info = Setting.objects.filter(key=key).first()
  19. if not info:
  20. return default
  21. return info.real_val
  22. @classmethod
  23. def set(cls, key, value, desc=None):
  24. if key in KEYS_DEFAULT:
  25. value = json.dumps(value)
  26. Setting.objects.update_or_create(key=key, defaults={'value': value, 'desc': desc})
  27. else:
  28. raise KeyError('invalid key')
  29. @classmethod
  30. def get_ssh_key(cls):
  31. public_key = cls.get_default('public_key')
  32. private_key = cls.get_default('private_key')
  33. if not private_key or not public_key:
  34. private_key, public_key = SSH.generate_key()
  35. cls.set('private_key', private_key)
  36. cls.set('public_key', public_key)
  37. return private_key, public_key