Refactor environment variable hydration logic. (#2321)
- 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>
This commit is contained in:
		| @@ -174,11 +174,11 @@ class Config(dict): | |||||||
|  |  | ||||||
|     def load_environment_vars(self, prefix=SANIC_PREFIX): |     def load_environment_vars(self, prefix=SANIC_PREFIX): | ||||||
|         """ |         """ | ||||||
|         Looks for prefixed environment variables and applies |         Looks for prefixed environment variables and applies them to the | ||||||
|         them to the configuration if present. This is called automatically when |         configuration if present. This is called automatically when Sanic | ||||||
|         Sanic starts up to load environment variables into config. |         starts up to load environment variables into config. | ||||||
|  |  | ||||||
|         It will automatically hyrdate the following types: |         It will automatically hydrate the following types: | ||||||
|  |  | ||||||
|         - ``int`` |         - ``int`` | ||||||
|         - ``float`` |         - ``float`` | ||||||
| @@ -186,19 +186,18 @@ class Config(dict): | |||||||
|  |  | ||||||
|         Anything else will be imported as a ``str``. |         Anything else will be imported as a ``str``. | ||||||
|         """ |         """ | ||||||
|         for k, v in environ.items(): |         for key, value in environ.items(): | ||||||
|             if k.startswith(prefix): |             if not key.startswith(prefix): | ||||||
|                 _, config_key = k.split(prefix, 1) |                 continue | ||||||
|  |  | ||||||
|  |             _, config_key = key.split(prefix, 1) | ||||||
|  |  | ||||||
|  |             for converter in (int, float, str_to_bool, str): | ||||||
|                 try: |                 try: | ||||||
|                     self[config_key] = int(v) |                     self[config_key] = converter(value) | ||||||
|  |                     break | ||||||
|                 except ValueError: |                 except ValueError: | ||||||
|                     try: |                     pass | ||||||
|                         self[config_key] = float(v) |  | ||||||
|                     except ValueError: |  | ||||||
|                         try: |  | ||||||
|                             self[config_key] = str_to_bool(v) |  | ||||||
|                         except ValueError: |  | ||||||
|                             self[config_key] = v |  | ||||||
|  |  | ||||||
|     def update_config(self, config: Union[bytes, str, dict, Any]): |     def update_config(self, config: Union[bytes, str, dict, Any]): | ||||||
|         """ |         """ | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user
	 Clay Sweetser
					Clay Sweetser