Explorar o código

Read environment secrets in state at import time (#5120)

Khaleel Al-Adhami hai 1 mes
pai
achega
44232fb0cd
Modificáronse 1 ficheiros con 25 adicións e 15 borrados
  1. 25 15
      reflex/config.py

+ 25 - 15
reflex/config.py

@@ -49,6 +49,29 @@ except ImportError:
     load_dotenv = None
 
 
+def _load_dotenv_from_str(env_files: str) -> None:
+    if not env_files:
+        return
+
+    if load_dotenv is None:
+        console.error(
+            """The `python-dotenv` package is required to load environment variables from a file. Run `pip install "python-dotenv>=1.0.1"`."""
+        )
+        return
+
+    # load env files in reverse order if they exist
+    for env_file_path in [
+        Path(p) for s in reversed(env_files.split(os.pathsep)) if (p := s.strip())
+    ]:
+        if env_file_path.exists():
+            load_dotenv(env_file_path, override=True)
+
+
+# Load the env files at import time if they are set in the ENV_FILE environment variable.
+if load_dotenv is not None and (env_files := os.getenv("ENV_FILE")):
+    _load_dotenv_from_str(env_files)
+
+
 class DBConfig(Base):
     """Database config."""
 
@@ -936,21 +959,8 @@ class Config(Base):
         Returns:
             The updated config values.
         """
-        env_file = self.env_file or os.environ.get("ENV_FILE", None)
-        if env_file:
-            if load_dotenv is None:
-                console.error(
-                    """The `python-dotenv` package is required to load environment variables from a file. Run `pip install "python-dotenv>=1.0.1"`."""
-                )
-            else:
-                # load env files in reverse order if they exist
-                for env_file_path in [
-                    Path(p)
-                    for s in reversed(env_file.split(os.pathsep))
-                    if (p := s.strip())
-                ]:
-                    if env_file_path.exists():
-                        load_dotenv(env_file_path, override=True)
+        if self.env_file:
+            _load_dotenv_from_str(self.env_file)
 
         updated_values = {}
         # Iterate over the fields.