Created
November 20, 2019 15:11
-
-
Save tejinderss/4113cdf9647ce0349f9567565525ce05 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Config(dict): | |
def __init__(self, root_path, defaults=None): | |
dict.__init__(self, defaults or {}) | |
self.root_path = root_path | |
def from_envvar(self, variable_name, silent=False): | |
"""Loads a configuration from an environment variable pointing to | |
a configuration file. This is basically just a shortcut with nicer | |
error messages for this line of code:: | |
app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) | |
:param variable_name: name of the environment variable | |
:param silent: set to ``True`` if you want silent failure for missing | |
files. | |
:return: bool. ``True`` if able to load config, ``False`` otherwise. | |
""" | |
rv = os.environ.get(variable_name) | |
if not rv: | |
if silent: | |
return False | |
raise RuntimeError( | |
"The environment variable %r is not set " | |
"and as such configuration could not be " | |
"loaded. Set this variable and make it " | |
"point to a configuration file" % variable_name | |
) | |
return self.from_pyfile(rv, silent=silent) | |
def from_pyfile(self, filename, silent=False): | |
"""Updates the values in the config from a Python file. This function | |
behaves as if the file was imported as module with the | |
:meth:`from_object` function. | |
:param filename: the filename of the config. This can either be an | |
absolute filename or a filename relative to the | |
root path. | |
:param silent: set to ``True`` if you want silent failure for missing | |
files. | |
""" | |
filename = os.path.join(self.root_path, filename) | |
d = types.ModuleType("config") | |
d.__file__ = filename | |
try: | |
with open(filename, mode="rb") as config_file: | |
exec(compile(config_file.read(), filename, "exec"), d.__dict__) | |
except IOError as e: | |
if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR): | |
return False | |
e.strerror = "Unable to load configuration file (%s)" % e.strerror | |
raise | |
self.from_object(d) | |
return True | |
def from_object(self, obj): | |
"""Updates the values from the given object. An object can be of one | |
of the following two types: | |
- a string: in this case the object with that name will be imported | |
- an actual object reference: that object is used directly | |
Objects are usually either modules or classes. :meth:`from_object` | |
loads only the uppercase attributes of the module/class. A ``dict`` | |
object will not work with :meth:`from_object` because the keys of a | |
``dict`` are not attributes of the ``dict`` class. | |
Example of module-based configuration:: | |
app.config.from_object('yourapplication.default_config') | |
from yourapplication import default_config | |
app.config.from_object(default_config) | |
Nothing is done to the object before loading. If the object is a | |
class and has ``@property`` attributes, it needs to be | |
instantiated before being passed to this method. | |
You should not use this function to load the actual configuration but | |
rather configuration defaults. The actual config should be loaded | |
with :meth:`from_pyfile` and ideally from a location not within the | |
package because the package might be installed system wide. | |
See :ref:`config-dev-prod` for an example of class-based configuration | |
using :meth:`from_object`. | |
:param obj: an import name or object | |
""" | |
if isinstance(obj, string_types): | |
obj = import_string(obj) | |
for key in dir(obj): | |
if key.isupper(): | |
self[key] = getattr(obj, key) | |
def from_file(self, filename, load, silent=False): | |
"""Update the values in the config from a file that is loaded | |
using the ``load`` parameter. The loaded data is passed to the | |
:meth:`from_mapping` method. | |
:param filename: The path to the data file. This can be an | |
absolute path or relative to the config root path. | |
:param load: A callable that takes a file handle and returns a | |
mapping of loaded data from the file. | |
:type load: ``Callable[[Reader], Mapping]`` where ``Reader`` | |
implements a ``read`` method. | |
:param silent: Ignore the file if it doesn't exist. | |
""" | |
filename = os.path.join(self.root_path, filename) | |
try: | |
with open(filename) as f: | |
obj = load(f) | |
except IOError as e: | |
if silent and e.errno in (errno.ENOENT, errno.EISDIR): | |
return False | |
e.strerror = "Unable to load configuration file (%s)" % e.strerror | |
raise | |
return self.from_mapping(obj) | |
def from_json(self, filename, silent=False): | |
"""Update the values in the config from a JSON file. The loaded | |
data is passed to the :meth:`from_mapping` method. | |
:param filename: The path to the JSON file. This can be an | |
absolute path or relative to the config root path. | |
:param silent: Ignore the file if it doesn't exist. | |
""" | |
warnings.warn( | |
"'from_json' is deprecated and will be removed in 2.0." | |
" Use 'from_file(filename, load=json.load)' instead.", | |
DeprecationWarning, | |
stacklevel=2, | |
) | |
from .json import load | |
return self.from_file(filename, load, silent=silent) | |
def from_mapping(self, *mapping, **kwargs): | |
mappings = [] | |
if len(mapping) == 1: | |
if hasattr(mapping[0], "items"): | |
mappings.append(mapping[0].items()) | |
else: | |
mappings.append(mapping[0]) | |
elif len(mapping) > 1: | |
raise TypeError( | |
"expected at most 1 positional argument, got %d" % len(mapping) | |
) | |
mappings.append(kwargs.items()) | |
for mapping in mappings: | |
for (key, value) in mapping: | |
if key.isupper(): | |
self[key] = value | |
return True | |
def get_namespace(self, namespace, lowercase=True, trim_namespace=True): | |
"""Returns a dictionary containing a subset of configuration options | |
that match the specified namespace/prefix. Example usage:: | |
app.config['IMAGE_STORE_TYPE'] = 'fs' | |
app.config['IMAGE_STORE_PATH'] = '/var/app/images' | |
app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' | |
image_store_config = app.config.get_namespace('IMAGE_STORE_') | |
The resulting dictionary `image_store_config` would look like:: | |
{ | |
'type': 'fs', | |
'path': '/var/app/images', | |
'base_url': 'http://img.website.com' | |
} | |
""" | |
rv = {} | |
for k, v in iteritems(self): | |
if not k.startswith(namespace): | |
continue | |
if trim_namespace: | |
key = k[len(namespace) :] | |
else: | |
key = k | |
if lowercase: | |
key = key.lower() | |
rv[key] = v | |
return rv | |
def __repr__(self): | |
return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment