Removes a given key from the given `.env` file. If the .env path given doesn't exist, fails. If the given key doesn't exist in the .env, fails.
(
dotenv_path: StrPath,
key_to_unset: str,
quote_mode: str = "always",
encoding: Optional[str] = "utf-8",
)
| 194 | |
| 195 | |
| 196 | def unset_key( |
| 197 | dotenv_path: StrPath, |
| 198 | key_to_unset: str, |
| 199 | quote_mode: str = "always", |
| 200 | encoding: Optional[str] = "utf-8", |
| 201 | ) -> Tuple[Optional[bool], str]: |
| 202 | """ |
| 203 | Removes a given key from the given `.env` file. |
| 204 | |
| 205 | If the .env path given doesn't exist, fails. |
| 206 | If the given key doesn't exist in the .env, fails. |
| 207 | """ |
| 208 | if not os.path.exists(dotenv_path): |
| 209 | logger.warning("Can't delete from %s - it doesn't exist.", dotenv_path) |
| 210 | return None, key_to_unset |
| 211 | |
| 212 | removed = False |
| 213 | with rewrite(dotenv_path, encoding=encoding) as (source, dest): |
| 214 | for mapping in with_warn_for_invalid_lines(parse_stream(source)): |
| 215 | if mapping.key == key_to_unset: |
| 216 | removed = True |
| 217 | else: |
| 218 | dest.write(mapping.original.string) |
| 219 | |
| 220 | if not removed: |
| 221 | logger.warning("Key %s not removed from %s - key doesn't exist.", key_to_unset, dotenv_path) |
| 222 | return None, key_to_unset |
| 223 | |
| 224 | return removed, key_to_unset |
| 225 | |
| 226 | |
| 227 | def resolve_variables( |
no test coverage detected