Skip to content

Commit

Permalink
Refactor environment variable hydration logic. (#2321)
Browse files Browse the repository at this point in the history
- Refactor environment variable hydration logic to be less nested. This allows possible future extension of the hydration logic.
- Fix a spelling mistake in `load_environment_vars` docstring.

Co-authored-by: Adam Hopkins <admhpkns@gmail.com>
  • Loading branch information
Varriount and ahopkins committed Dec 2, 2021
1 parent a8d55e1 commit f641830
Showing 1 changed file with 14 additions and 15 deletions.
29 changes: 14 additions & 15 deletions sanic/config.py
Expand Up @@ -174,31 +174,30 @@ def _check_error_format(self):

def load_environment_vars(self, prefix=SANIC_PREFIX):
"""
Looks for prefixed environment variables and applies
them to the configuration if present. This is called automatically when
Sanic starts up to load environment variables into config.
Looks for prefixed environment variables and applies them to the
configuration if present. This is called automatically when Sanic
starts up to load environment variables into config.
It will automatically hyrdate the following types:
It will automatically hydrate the following types:
- ``int``
- ``float``
- ``bool``
Anything else will be imported as a ``str``.
"""
for k, v in environ.items():
if k.startswith(prefix):
_, config_key = k.split(prefix, 1)
for key, value in environ.items():
if not key.startswith(prefix):
continue

_, config_key = key.split(prefix, 1)

for converter in (int, float, str_to_bool, str):
try:
self[config_key] = int(v)
self[config_key] = converter(value)
break
except ValueError:
try:
self[config_key] = float(v)
except ValueError:
try:
self[config_key] = str_to_bool(v)
except ValueError:
self[config_key] = v
pass

def update_config(self, config: Union[bytes, str, dict, Any]):
"""
Expand Down

0 comments on commit f641830

Please sign in to comment.