config_parser.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import sys
  2. from os import chdir, environ, getcwd, path
  3. import hiyapyco
  4. import yaml
  5. import lakesuperior
  6. default_config_dir = environ.get(
  7. 'FCREPO_CONFIG_DIR',
  8. path.join(
  9. path.dirname(path.abspath(lakesuperior.__file__)), 'etc.defaults'))
  10. """
  11. Default configuration directory.
  12. This value falls back to the provided ``etc.defaults`` directory if the
  13. ``FCREPO_CONFIG_DIR`` environment variable is not set.
  14. This value can still be overridden by custom applications by passing the
  15. ``config_dir`` value to :func:`parse_config` explicitly.
  16. """
  17. def parse_config(config_dir=None):
  18. """
  19. Parse configuration from a directory.
  20. This is normally called by the standard endpoints (``lsup_admin``, web
  21. server, etc.) or by a Python client by importing
  22. :py:mod:`lakesuperior.env_setup` but an application using a non-default
  23. configuration may specify an alternative configuration directory.
  24. The directory must have the same structure as the one provided in
  25. ``etc.defaults``.
  26. :param config_dir: Location on the filesystem of the configuration
  27. directory. The default is set by the ``FCREPO_CONFIG_DIR`` environment
  28. variable or, if this is not set, the ``etc.defaults`` stock directory.
  29. """
  30. configs = (
  31. 'application',
  32. 'logging',
  33. 'namespaces',
  34. 'flask',
  35. )
  36. if not config_dir:
  37. config_dir = default_config_dir
  38. # This will hold a dict of all configuration values.
  39. _config = {}
  40. print('Reading configuration at {}'.format(config_dir))
  41. for cname in configs:
  42. file = path.join(config_dir, '{}.yml'.format(cname))
  43. with open(file, 'r') as stream:
  44. _config[cname] = yaml.load(stream, yaml.SafeLoader)
  45. if not _config['application']['data_dir']:
  46. _config['application']['data_dir'] = path.join(
  47. lakesuperior.basedir, 'data')
  48. data_dir = _config['application']['data_dir']
  49. _config['application']['store']['ldp_nr']['location'] = path.join(
  50. data_dir, 'ldpnr_store')
  51. _config['application']['store']['ldp_rs']['location'] = path.join(
  52. data_dir, 'ldprs_store')
  53. # If log handler file names are relative, they will be relative to the
  54. # data dir.
  55. oldwd = getcwd()
  56. chdir(data_dir)
  57. for handler in _config['logging']['handlers'].values():
  58. if 'filename' in handler:
  59. handler['filename'] = path.realpath(handler['filename'])
  60. chdir(oldwd)
  61. return _config
  62. # Load default configuration.
  63. config = parse_config()