config.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.config
  4. ~~~~~~~~~~~~
  5. Implements the configuration related objects.
  6. :copyright: (c) 2011 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import imp
  10. import os
  11. import errno
  12. from werkzeug.utils import import_string
  13. from ._compat import string_types
  14. class ConfigAttribute(object):
  15. """Makes an attribute forward to the config"""
  16. def __init__(self, name, get_converter=None):
  17. self.__name__ = name
  18. self.get_converter = get_converter
  19. def __get__(self, obj, type=None):
  20. if obj is None:
  21. return self
  22. rv = obj.config[self.__name__]
  23. if self.get_converter is not None:
  24. rv = self.get_converter(rv)
  25. return rv
  26. def __set__(self, obj, value):
  27. obj.config[self.__name__] = value
  28. class Config(dict):
  29. """Works exactly like a dict but provides ways to fill it from files
  30. or special dictionaries. There are two common patterns to populate the
  31. config.
  32. Either you can fill the config from a config file::
  33. app.config.from_pyfile('yourconfig.cfg')
  34. Or alternatively you can define the configuration options in the
  35. module that calls :meth:`from_object` or provide an import path to
  36. a module that should be loaded. It is also possible to tell it to
  37. use the same module and with that provide the configuration values
  38. just before the call::
  39. DEBUG = True
  40. SECRET_KEY = 'development key'
  41. app.config.from_object(__name__)
  42. In both cases (loading from any Python file or loading from modules),
  43. only uppercase keys are added to the config. This makes it possible to use
  44. lowercase values in the config file for temporary values that are not added
  45. to the config or to define the config keys in the same file that implements
  46. the application.
  47. Probably the most interesting way to load configurations is from an
  48. environment variable pointing to a file::
  49. app.config.from_envvar('YOURAPPLICATION_SETTINGS')
  50. In this case before launching the application you have to set this
  51. environment variable to the file you want to use. On Linux and OS X
  52. use the export statement::
  53. export YOURAPPLICATION_SETTINGS='/path/to/config/file'
  54. On windows use `set` instead.
  55. :param root_path: path to which files are read relative from. When the
  56. config object is created by the application, this is
  57. the application's :attr:`~flask.Flask.root_path`.
  58. :param defaults: an optional dictionary of default values
  59. """
  60. def __init__(self, root_path, defaults=None):
  61. dict.__init__(self, defaults or {})
  62. self.root_path = root_path
  63. def from_envvar(self, variable_name, silent=False):
  64. """Loads a configuration from an environment variable pointing to
  65. a configuration file. This is basically just a shortcut with nicer
  66. error messages for this line of code::
  67. app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
  68. :param variable_name: name of the environment variable
  69. :param silent: set to `True` if you want silent failure for missing
  70. files.
  71. :return: bool. `True` if able to load config, `False` otherwise.
  72. """
  73. rv = os.environ.get(variable_name)
  74. if not rv:
  75. if silent:
  76. return False
  77. raise RuntimeError('The environment variable %r is not set '
  78. 'and as such configuration could not be '
  79. 'loaded. Set this variable and make it '
  80. 'point to a configuration file' %
  81. variable_name)
  82. return self.from_pyfile(rv, silent=silent)
  83. def from_pyfile(self, filename, silent=False):
  84. """Updates the values in the config from a Python file. This function
  85. behaves as if the file was imported as module with the
  86. :meth:`from_object` function.
  87. :param filename: the filename of the config. This can either be an
  88. absolute filename or a filename relative to the
  89. root path.
  90. :param silent: set to `True` if you want silent failure for missing
  91. files.
  92. .. versionadded:: 0.7
  93. `silent` parameter.
  94. """
  95. filename = os.path.join(self.root_path, filename)
  96. d = imp.new_module('config')
  97. d.__file__ = filename
  98. try:
  99. with open(filename) as config_file:
  100. exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
  101. except IOError as e:
  102. if silent and e.errno in (errno.ENOENT, errno.EISDIR):
  103. return False
  104. e.strerror = 'Unable to load configuration file (%s)' % e.strerror
  105. raise
  106. self.from_object(d)
  107. return True
  108. def from_object(self, obj):
  109. """Updates the values from the given object. An object can be of one
  110. of the following two types:
  111. - a string: in this case the object with that name will be imported
  112. - an actual object reference: that object is used directly
  113. Objects are usually either modules or classes.
  114. Just the uppercase variables in that object are stored in the config.
  115. Example usage::
  116. app.config.from_object('yourapplication.default_config')
  117. from yourapplication import default_config
  118. app.config.from_object(default_config)
  119. You should not use this function to load the actual configuration but
  120. rather configuration defaults. The actual config should be loaded
  121. with :meth:`from_pyfile` and ideally from a location not within the
  122. package because the package might be installed system wide.
  123. :param obj: an import name or object
  124. """
  125. if isinstance(obj, string_types):
  126. obj = import_string(obj)
  127. for key in dir(obj):
  128. if key.isupper():
  129. self[key] = getattr(obj, key)
  130. def __repr__(self):
  131. return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))