A corporation manager and dashboard for EVE Online
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

92 lines
2.6 KiB

  1. # -*- coding: utf-8 -*-
  2. import yaml
  3. from .module import Module
  4. __all__ = ["Config"]
  5. class _ModuleIndex(list):
  6. """List class that supports attribute access to its elements by key."""
  7. def __init__(self):
  8. super().__init__()
  9. self._index = {}
  10. def __getitem__(self, key):
  11. try:
  12. return super().__getitem__(key)
  13. except TypeError:
  14. return super().__getitem__(self._index[key])
  15. def __getattr__(self, attr):
  16. return self[self._index[attr]]
  17. def append(self, key, value):
  18. self._index[key] = len(self)
  19. super().append(value)
  20. class Config:
  21. """Stores application-wide configuration info."""
  22. def __init__(self, confdir):
  23. self._dir = confdir
  24. self._filename = confdir / "config.yml"
  25. self._data = None
  26. self._modules = _ModuleIndex()
  27. self._load()
  28. def _load(self):
  29. """Load config from the config file."""
  30. with self._filename.open("rb") as fp:
  31. self._data = yaml.load(fp)
  32. self._modules = _ModuleIndex()
  33. for name in self.get("modules.enabled", []):
  34. self._modules.append(name, Module(self, name))
  35. def get(self, key="", default=None):
  36. """Acts like a dict lookup in the config file.
  37. Dots can be used to separate keys. For example,
  38. config["foo.bar"] == config["foo"]["bar"].
  39. """
  40. obj = self._data
  41. for item in key.split("."):
  42. if item not in obj:
  43. return default
  44. obj = obj[item]
  45. return obj
  46. @property
  47. def modules(self):
  48. """Return a list-like object (a _ModuleIndex) of loaded modules."""
  49. return self._modules
  50. @property
  51. def scheme(self):
  52. """Return the site's configured scheme, either "http" or "https"."""
  53. return "https" if self.get("site.https") else "http"
  54. def install(self, app):
  55. """Install relevant config into the application, including modules."""
  56. app.config["SERVER_NAME"] = self.get("site.canonical")
  57. app.config["PREFERRED_URL_SCHEME"] = self.scheme
  58. app.secret_key = self.get("auth.session_key")
  59. for module in self.modules:
  60. module.install(app)
  61. def load_module_config(self, name):
  62. """Load and return a module config file.
  63. Returns a YAML parse of {confdir}/modules/{name}.yml, or None.
  64. """
  65. filename = self._dir / "modules" / (name + ".yml")
  66. try:
  67. with filename.open("rb") as fp:
  68. return yaml.load(fp)
  69. except FileNotFoundError:
  70. return None