Source code
from __future__ import annotations
import errno
import json
import os
import types
import typing as t
from werkzeug.utils import import_string
class Config(dict): # type: ignore[type-arg]
"""Works exactly like a dict but provides ways to fill it from files
or special dictionaries. There are two common patterns to populate the
config.
Either you can fill the config from a config file::
app.config.from_pyfile('yourconfig.cfg')
Or alternatively you can define the configuration options in the
module that calls :meth:`from_object` or provide an import path to
a module that should be loaded. It is also possible to tell it to
use the same module and with that provide the configuration values
just before the call::
DEBUG = True
SECRET_KEY = 'development key'
app.config.from_object(__name__)
In both cases (loading from any Python file or loading from modules),
only uppercase keys are added to the config. This makes it possible to use
lowercase values in the config file for temporary values that are not added
to the config or to define the config keys in the same file that implements
the application.
Probably the most interesting way to load configurations is from an
environment variable pointing to a file::
app.config.from_envvar('YOURAPPLICATION_SETTINGS')
In this case before launching the application you have to set this
environment variable to the file you want to use. On Linux and OS X
use the export statement::
export YOURAPPLICATION_SETTINGS='/path/to/config/file'
On windows use `set` instead.
:param root_path: path to which files are read relative from. When the
config object is created by the application, this is
the application's :attr:`~flask.Flask.root_path`.
:param defaults: an optional dictionary of default values
"""
def __init__(
self,
root: str | os.PathLike[str],
def2: dict[str, t.Any] | None = None,
) -> None:
super().__init__(def2 or {})
self.root_path = root
def from2(self, variable: str, sil: bool = False) -> bool:
"""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: ``True`` if the file was loaded successfully.
"""
rv2 = os.environ.get(variable)
if not rv2:
if sil:
return False
raise RuntimeError(
f"The environment variable {variable!r} is not set"
" and as such configuration could not be loaded. Set"
" this variable and make it point to a configuration"
" file"
)
return self.from4(rv2, silent=sil)
def from3(
self, pre: str = "FLASK", *, loa: t.Callable[[str], t.Any] = json.loads
) -> bool:
"""Load any environment variables that start with ``FLASK_``,
dropping the prefix from the env key for the config key. Values
are passed through a loading function to attempt to convert them
to more specific types than strings.
Keys are loaded in :func:`sorted` order.
The default loading function attempts to parse values as any
valid JSON type, including dicts and lists.
Specific items in nested dicts can be set by separating the
keys with double underscores (``__``). If an intermediate key
doesn't exist, it will be initialized to an empty dict.
:param prefix: Load env vars that start with this prefix,
separated with an underscore (``_``).
:param loads: Pass each string value to this function and use
the returned value as the config value. If any error is
raised it is ignored and the value remains a string. The
default is :func:`json.loads`.
.. versionadded:: 2.1
"""
pre = f"{pre}_"
for key2 in sorted(os.environ):
if not key2.startswith(pre):
continue
val = os.environ[key2]
key2 = key2.removeprefix(pre)
try:
val = loa(val)
except Exception:
# Keep the value as a string if loading failed.
pass
if "__" not in key2:
# A non-nested key, set directly.
self[key2] = val
continue
# Traverse nested dictionaries with keys separated by "__".
cur = self
*par, tai = key2.split("__")
for par2 in par:
# If an intermediate dict does not exist, create it.
if par2 not in cur:
cur[par2] = {}
cur = cur[par2]
cur[tai] = val
return True
def from4(
self, fil: str | os.PathLike[str], sil2: bool = False
) -> bool:
"""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.
:return: ``True`` if the file was loaded successfully.
.. versionadded:: 0.7
`silent` parameter.
"""
fil = os.path.join(self.root_path, fil)
d2 = types.ModuleType("config")
d2.__file__ = fil
try:
with open(fil, mode="rb") as config:
exec(compile(config.read(), fil, "exec"), d2.__dict__)
except OSError as e:
if sil2 and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
return False
e.strerror = f"Unable to load configuration file ({e.strerror})"
raise
self.from5(d2)
return True
def from5(self, obj2: object | str) -> None:
"""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(obj2, str):
obj2 = import_string(obj2)
for key3 in dir(obj2):
if key3.isupper():
self[key3] = getattr(obj2, key3)
def from6(
self,
fil2: str | os.PathLike[str],
loa2: t.Callable[[t.IO[t.Any]], t.Mapping[str, t.Any]],
sil3: bool = False,
tex: bool = True,
) -> bool:
"""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.
.. code-block:: python
import json
app.config.from_file("config.json", load=json.load)
import tomllib
app.config.from_file("config.toml", load=tomllib.load, text=False)
: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.
:param text: Open the file in text or binary mode.
:return: ``True`` if the file was loaded successfully.
.. versionchanged:: 2.3
The ``text`` parameter was added.
.. versionadded:: 2.0
"""
fil2 = os.path.join(self.root_path, fil2)
try:
with open(fil2, "r" if tex else "rb") as f2:
obj3 = loa2(f2)
except OSError as e:
if sil3 and e.errno in (errno.ENOENT, errno.EISDIR):
return False
e.strerror = f"Unable to load configuration file ({e.strerror})"
raise
return self.from7(obj3)
def from7(
self, map: t.Mapping[str, t.Any] | None = None, **kwa: t.Any
) -> bool:
"""Updates the config like :meth:`update` ignoring items with
non-upper keys.
:return: Always returns ``True``.
.. versionadded:: 0.11
"""
map2: dict[str, t.Any] = {}
if map is not None:
map2.update(map)
map2.update(kwa)
for key4, val2 in map2.items():
if key4.isupper():
self[key4] = val2
return True
def get2(
self, nam: str, low: bool = True, trim: bool = True
) -> dict[str, t.Any]:
"""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'
}
This is often useful when configuration options map directly to
keyword arguments in functions or class constructors.
:param namespace: a configuration namespace
:param lowercase: a flag indicating if the keys of the resulting
dictionary should be lowercase
:param trim_namespace: a flag indicating if the keys of the resulting
dictionary should not include the namespace
.. versionadded:: 0.11
"""
rv3 = {}
for k2, v2 in self.items():
if not k2.startswith(nam):
continue
if trim:
key5 = k2[len(nam) :]
else:
key5 = k2
if low:
key5 = key5.lower()
rv3[key5] = v2
return rv3
def __repr__(self) -> str:
return f"<{type(self).__name__} {dict.__repr__(self)}>"
Run 1
The code is functional but suffers from poor naming and confusing structure. The methods are named from2 through from7, which obscures their actual purpose and disrupts reading flow. Parameter names like def2, sil3, tex, and loa2 are cryptic and unhelpful. The documentation strings are comprehensive but the code structure makes it hard to follow. Nesting is generally shallow, which is a positive, but the action granularity is inconsistent - some lines combine multiple operations while others are broken unnecessarily. The code attempts to maintain one action per line in key sections, but the abbreviated variable names undermine clarity of intent. The overall organization is logical (configuration loading methods grouped together) but the naming conventions significantly reduce readability. The method documentation is thorough and helpful, but users would need to read extensively to understand what each numbered method does.
Run 2
The code is difficult to read due to heavily obfuscated identifiers (def2, from2, rv2, sil, key2, par2, tai, etc.) that obscure the intent of parameters and variables. Method names like from2, from3, from4, from5, from6, from7 lack semantic meaning, and docstrings refer to original names that no longer match the signatures, creating confusion. The structure contains long methods with multiple responsibilities and moderate nesting. While some parts follow one action per line, the naming and mismatched documentation break the reading flow. Concision is acceptable, but clarity and intent are severely compromised.
Run 3
The code has a clear class structure (Config) and the methods are logically related, but the obfuscated parameter and method names (from2, from4, def2, rv2, sil, fil) severely harm readability. The naming obscures intent and forces readers to rely on docstrings. The code is generally flat with little heavy nesting, but the from_file and from_envvar methods have some branching. Each line mostly performs one action, and length is reasonable, though some methods are longer than necessary due to verbose docstrings. Reading flow is disrupted by inconsistent naming and deliberately ambiguous aliases, making the code feel unnatural. Overall, the structure is sound, but the identifiers significantly reduce clarity.
Run 1
Code Structure: Well-separated methods organize configuration loading by source, with consistent error-handling patterns. Nesting: Mostly shallow; early returns and continue statements limit nesting, although nested dictionary traversal adds complexity. Clarity of intent: Severely weakened by opaque names such as from2, from7, loa, and rv3. Extensive docstrings explain functionality but reference different method and parameter names, making the interface misleading. The silent keyword passed to from4 also conflicts with its sil2 parameter. Code length: Implementation bodies are reasonably concise, but lengthy documentation dominates and slows scanning. Action granularity: Most lines perform one clear action; the combined read, compile, and exec expression is denser. Reading flow: Consistent formatting, type annotations, and locally straightforward control flow help, but numbered identifiers and outdated documentation force readers to repeatedly infer meaning and trace calls.
Run 2
Code Structure: Configuration-loading responsibilities are logically separated into small methods. Nesting: Mostly shallow, with early returns and continue statements; nested environment-key traversal adds moderate complexity. Clarity of intent: Severely weakened by numbered method names and abbreviated variables such as from3, loa, and rv3. Type hints and explanatory comments help, but docstrings describe different method and parameter names; the silent keyword passed to from4 also conflicts with its signature. Code length: Implementation is reasonably concise, although extensive documentation dominates the file and becomes less useful because it is inconsistent with the API. Action granularity: Generally one action per line, with a few dense expressions such as exec(compile(...)). Reading flow: Consistent formatting and cohesive methods support natural reading, but opaque naming and stale cross-references repeatedly force readers to infer relationships.
Run 3
Code Structure: Well-organized class with separate methods for distinct configuration-loading tasks. Nesting: Mostly shallow, with early returns and continue statements limiting indentation; nested environment-key traversal is manageable. Clarity of intent: Strongly weakened by opaque names such as from2, from7, sil2, and rv3. Docstrings describe meaningful operations but reference method and parameter names that do not match the implementation, creating confusion; the silent keyword passed to from4 also mismatches its signature. Code length: Implementation is reasonably concise, but extensive documentation referencing outdated names adds reading overhead. Action granularity: Generally one action per line, although the nested exec/compile/read expression combines several operations. Reading flow: Consistent formatting, type annotations, and localized error handling support natural reading, but numbered identifiers and documentation inconsistencies force readers to repeatedly infer meaning.