@@ -109,23 +109,30 @@ def get(self, key: str) -> Optional[str]:
109109 return None
110110
111111
112- def get_key (dotenv_path : Union [str , _PathLike ], key_to_get : str ) -> Optional [str ]:
112+ def get_key (
113+ dotenv_path : Union [str , _PathLike ],
114+ key_to_get : str ,
115+ encoding : Optional [str ] = "utf-8" ,
116+ ) -> Optional [str ]:
113117 """
114- Gets the value of a given key from the given .env
118+ Get the value of a given key from the given .env.
115119
116- If the .env path given doesn't exist, fails
120+ Returns `None` if the key isn't found or doesn't have a value.
117121 """
118- return DotEnv (dotenv_path , verbose = True ).get (key_to_get )
122+ return DotEnv (dotenv_path , verbose = True , encoding = encoding ).get (key_to_get )
119123
120124
121125@contextmanager
122- def rewrite (path : Union [str , _PathLike ]) -> Iterator [Tuple [IO [str ], IO [str ]]]:
126+ def rewrite (
127+ path : Union [str , _PathLike ],
128+ encoding : Optional [str ],
129+ ) -> Iterator [Tuple [IO [str ], IO [str ]]]:
123130 try :
124131 if not os .path .isfile (path ):
125- with io .open (path , "w+" ) as source :
132+ with io .open (path , "w+" , encoding = encoding ) as source :
126133 source .write ("" )
127- with tempfile .NamedTemporaryFile (mode = "w+" , delete = False ) as dest :
128- with io .open (path ) as source :
134+ with tempfile .NamedTemporaryFile (mode = "w+" , delete = False , encoding = encoding ) as dest :
135+ with io .open (path , encoding = encoding ) as source :
129136 yield (source , dest ) # type: ignore
130137 except BaseException :
131138 if os .path .isfile (dest .name ):
@@ -141,6 +148,7 @@ def set_key(
141148 value_to_set : str ,
142149 quote_mode : str = "always" ,
143150 export : bool = False ,
151+ encoding : Optional [str ] = "utf-8" ,
144152) -> Tuple [Optional [bool ], str , str ]:
145153 """
146154 Adds or Updates a key/value to the given .env
@@ -165,7 +173,7 @@ def set_key(
165173 else :
166174 line_out = "{}={}\n " .format (key_to_set , value_out )
167175
168- with rewrite (dotenv_path ) as (source , dest ):
176+ with rewrite (dotenv_path , encoding = encoding ) as (source , dest ):
169177 replaced = False
170178 missing_newline = False
171179 for mapping in with_warn_for_invalid_lines (parse_stream (source )):
@@ -187,6 +195,7 @@ def unset_key(
187195 dotenv_path : Union [str , _PathLike ],
188196 key_to_unset : str ,
189197 quote_mode : str = "always" ,
198+ encoding : Optional [str ] = "utf-8" ,
190199) -> Tuple [Optional [bool ], str ]:
191200 """
192201 Removes a given key from the given .env
@@ -199,7 +208,7 @@ def unset_key(
199208 return None , key_to_unset
200209
201210 removed = False
202- with rewrite (dotenv_path ) as (source , dest ):
211+ with rewrite (dotenv_path , encoding = encoding ) as (source , dest ):
203212 for mapping in with_warn_for_invalid_lines (parse_stream (source )):
204213 if mapping .key == key_to_unset :
205214 removed = True
0 commit comments