File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Original file line number Diff line number Diff line change @@ -578,7 +578,7 @@ def __call__(self) -> dict[str, Any]:
578
578
# As `extra` config is allowed in dotenv settings source, We have to
579
579
# update data with extra env variabels from dotenv file.
580
580
for env_name , env_value in self .env_vars .items ():
581
- if env_value is not None :
581
+ if env_name . startswith ( self . env_prefix ) and env_value is not None :
582
582
env_name_without_prefix = env_name [self .env_prefix_len :]
583
583
first_key , * _ = env_name_without_prefix .split (self .env_nested_delimiter )
584
584
Original file line number Diff line number Diff line change @@ -680,6 +680,37 @@ class Settings(BaseSettings):
680
680
assert s .c == 'best string'
681
681
682
682
683
+ prefix_test_env_file = """\
684
+ # this is a comment
685
+ prefix_A=good string
686
+ # another one, followed by whitespace
687
+
688
+ prefix_b='better string'
689
+ prefix_c="best string"
690
+ f="random value"
691
+ """
692
+
693
+
694
+ @pytest .mark .skipif (not dotenv , reason = 'python-dotenv not installed' )
695
+ def test_env_file_with_env_prefix (env , tmp_path ):
696
+ p = tmp_path / '.env'
697
+ p .write_text (prefix_test_env_file )
698
+
699
+ class Settings (BaseSettings ):
700
+ a : str
701
+ b : str
702
+ c : str
703
+
704
+ model_config = ConfigDict (env_file = p , env_prefix = 'prefix_' )
705
+
706
+ env .set ('prefix_A' , 'overridden var' )
707
+
708
+ s = Settings ()
709
+ assert s .a == 'overridden var'
710
+ assert s .b == 'better string'
711
+ assert s .c == 'best string'
712
+
713
+
683
714
@pytest .mark .skipif (not dotenv , reason = 'python-dotenv not installed' )
684
715
def test_env_file_config_case_sensitive (tmp_path ):
685
716
p = tmp_path / '.env'
You can’t perform that action at this time.
0 commit comments