ext_yaml_configobj.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """
  2. The Yaml ConfigObj Extension is a combination of the
  3. :class:`YamlConfigHandler` and :class:`ConfigObjConfigHandler` which allows
  4. the application to read Yaml configuration files into a ConfigObj based
  5. configuration handler.
  6. Requirements
  7. ------------
  8. * ConfigObj (``pip install configobj``)
  9. * pyYaml (``pip install pyYaml``)
  10. Configuration
  11. -------------
  12. This extension does not honor any application configuration settings.
  13. Usage
  14. -----
  15. **myapp.conf**
  16. .. code-block:: yaml
  17. ---
  18. myapp:
  19. foo: bar
  20. **myapp.py**
  21. .. code-block:: python
  22. from cement.core.foundation import CementApp
  23. class MyApp(CementApp):
  24. class Meta:
  25. label = 'myapp'
  26. extensions = ['yaml_configobj']
  27. config_handler = 'yaml_configobj'
  28. with MyApp() as app:
  29. app.run()
  30. # get config settings
  31. app.config['myapp']['foo']
  32. # set config settings
  33. app.config['myapp']['foo'] = 'bar2'
  34. # etc...
  35. """
  36. import os
  37. import yaml
  38. from ..utils.misc import minimal_logger
  39. from ..utils.fs import abspath
  40. from ..ext.ext_configobj import ConfigObjConfigHandler
  41. LOG = minimal_logger(__name__)
  42. class YamlConfigObjConfigHandler(ConfigObjConfigHandler):
  43. """
  44. This class implements the :ref:`IConfig <cement.core.config>`
  45. interface, and provides the same functionality of
  46. :ref:`ConfigObjConfigHandler <cement.ext.ext_configobj>`
  47. but with YAML configuration files. See
  48. `pyYAML <http://pyyaml.org/wiki/PyYAMLDocumentation>`_ for more
  49. information on pyYAML
  50. **Note** This extension has an external dependency on `pyYAML` and
  51. `ConfigObj`. You must include `pyYAML` and `configobj` in your
  52. application's dependencies as Cement explicitly does *not* include
  53. external dependencies for optional extensions.
  54. """
  55. class Meta:
  56. """Handler meta-data."""
  57. label = 'yaml_configobj'
  58. def __init__(self, *args, **kw):
  59. super(YamlConfigObjConfigHandler, self).__init__(*args, **kw)
  60. def _parse_file(self, file_path):
  61. """
  62. Parse YAML configuration file settings from file_path, overwriting
  63. existing config settings. If the file does not exist, returns False.
  64. :param file_path: The file system path to the YAML configuration file.
  65. :returns: boolean
  66. """
  67. self.merge(yaml.load(open(file_path)))
  68. # FIX ME: Should check that file was read properly, however if not it
  69. # will likely raise an exception anyhow.
  70. return True
  71. def load(app):
  72. app.handler.register(YamlConfigObjConfigHandler)