Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add DotEnv dumps/dump #503

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/dotenv/main.py
Expand Up @@ -113,6 +113,43 @@ def get(self, key: str) -> Optional[str]:

return None

def from_dict(self, data: Dict[str, Optional[str]], override: bool = False) -> None:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this should be a classmethod

"""
Create a DotEnv from a dictionary.
"""
for key, value in data.items():
if value is not None:
if not override and key in self.dict().keys():
if self.verbose:
logger.warning(
"Key %s already exists and will not be overwritten.",
key,
)
continue

if not self._dict:
self._dict = OrderedDict()
self._dict[key] = value

def dumps(self) -> str:
"""
Serialize the instance as a string.
"""
output = ""
for k, v in self.dict().items():
if v is not None:
output += f"{k}={v}\n"
return output

def dump(self) -> None:
"""
Write the instance to the .env file.
"""

if self.dotenv_path and os.path.isfile(self.dotenv_path):
with open(self.dotenv_path, "w", encoding=self.encoding) as f:
f.write(self.dumps())


def get_key(
dotenv_path: StrPath,
Expand Down
15 changes: 15 additions & 0 deletions tests/test_main.py
Expand Up @@ -3,6 +3,7 @@
import os
import sys
import textwrap
from typing import Dict, Optional
from unittest import mock

import pytest
Expand Down Expand Up @@ -399,3 +400,17 @@ def test_dotenv_values_file_stream(dotenv_path):
result = dotenv.dotenv_values(stream=f)

assert result == {"a": "b"}


def test_from_dict_and_dumps(dotenv_path):
data: Dict[str, Optional[str]] = {"a": "b", "c": "d"}

de = dotenv.main.DotEnv(dotenv_path)
de.from_dict(data)
de_str = de.dumps()

assert de_str == "a=b\nc=d\n"

de.dump()

assert dotenv_path.read_text() == de_str