config_parser.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import sys
  2. from os import path, environ
  3. import hiyapyco
  4. import yaml
  5. def parse_config(config_dir=None):
  6. """
  7. Parse configuration from a directory.
  8. This is normally called by the standard endpoints (``lsup_admin``, web
  9. server, etc.) or by a Python client by importing
  10. :py:mod:`lakesuperior.env_setup` but an application using a non-default
  11. configuration may specify an alternative configuration directory.
  12. The directory must have the same structure as the one provided in
  13. ``etc.defaults``.
  14. :param config_dir: Location on the filesystem of the configuration
  15. directory. The default is set by the ``FCREPO_CONFIG_DIR`` environment
  16. variable or, if this is not set, the ``etc.defaults`` stock directory.
  17. """
  18. configs = (
  19. 'application',
  20. 'logging',
  21. 'namespaces',
  22. 'flask',
  23. )
  24. if not config_dir:
  25. config_dir = environ.get('FCREPO_CONFIG_DIR', path.dirname(
  26. path.dirname(path.abspath(__file__))) + '/etc.defaults')
  27. # This will hold a dict of all configuration values.
  28. _config = {}
  29. print('Reading configuration at {}'.format(config_dir))
  30. for cname in configs:
  31. file = '{}/{}.yml'.format(config_dir , cname)
  32. with open(file, 'r') as stream:
  33. _config[cname] = yaml.load(stream, yaml.SafeLoader)
  34. error_msg = '''
  35. **************
  36. ** WARNING! **
  37. **************
  38. Your test {} store location is set to be the same as the production
  39. location. This means that if you run a test suite, your live data may be
  40. wiped clean!
  41. Please review your configuration before starting.
  42. '''
  43. # Merge default and test configurations.
  44. _test_config = {'application': hiyapyco.load(
  45. config_dir + '/application.yml',
  46. config_dir + '/test.yml', method=hiyapyco.METHOD_MERGE)}
  47. if _config['application']['store']['ldp_rs']['location'] \
  48. == _test_config['application']['store']['ldp_rs']['location']:
  49. raise RuntimeError(error_msg.format('RDF'))
  50. sys.exit()
  51. if _config['application']['store']['ldp_nr']['path'] \
  52. == _test_config['application']['store']['ldp_nr']['path']:
  53. raise RuntimeError(error_msg.format('binary'))
  54. sys.exit()
  55. return _config, _test_config
  56. # Load default configuration.
  57. config, test_config = parse_config()