dotenvplus 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dotenvplus/__init__.py ADDED
@@ -0,0 +1,163 @@
1
+ import re
2
+
3
+ from typing import Any, Iterator, Optional, Tuple, List, Dict
4
+
5
+ __version__ = "0.0.1"
6
+
7
+
8
+ class ParsingError(Exception):
9
+ pass
10
+
11
+
12
+ class DotEnv:
13
+ """
14
+ DotEnv is a dotenv parser for Python with additional type support.
15
+ It supports parsing of string, integer, float, and boolean values.
16
+
17
+ Arguments
18
+ ---------
19
+ path: `str` | `None`
20
+ The path to the .env file.
21
+ If none are provided, it defaults to `./.env`
22
+ handle_key_not_found: `bool`
23
+ If True, it will make the object return `None` for any key that is not found.
24
+ Essentially simulating `dict().get("Key", None)`
25
+
26
+ Raises
27
+ ------
28
+ `FileNotFoundError`
29
+ If the file_path is not a valid path.
30
+ `ParsingError`
31
+ If one of the values cannot be parsed.
32
+ """
33
+ def __init__(
34
+ self,
35
+ path: Optional[str] = None,
36
+ *,
37
+ handle_key_not_found: bool = False,
38
+ ):
39
+ # RegEx patterns
40
+ self.__re_keyvar = re.compile(r"^\s*([a-zA-Z0-9_]*)\s*=\s*(.+)$")
41
+ self.__re_isdigit = re.compile(r"^(?:-)?\d+$")
42
+ self.__re_isfloat = re.compile(r"^(?:-)?\d+\.\d+$")
43
+ self.__re_var_call = re.compile(r"\$\{([a-zA-Z0-9_]*)\}")
44
+
45
+ # General values
46
+ self.__env: Dict[str, Any] = {}
47
+ self.__quotes: Tuple[str, ...] = ("\"", "'")
48
+
49
+ # Config for the parser
50
+ self.__path: str = path or ".env"
51
+ self.__handle_key_not_found: bool = handle_key_not_found
52
+
53
+ # Finally, the parser
54
+ self.__parser()
55
+
56
+ def __repr__(self) -> str:
57
+ return f"<DotEnv data={self.__env}>"
58
+
59
+ def __getitem__(self, key: str) -> Any:
60
+ if self.__handle_key_not_found:
61
+ return self.__env.get(key, None)
62
+ return self.__env[key]
63
+
64
+ def __str__(self) -> str:
65
+ return str(self.__env)
66
+
67
+ def __int__(self) -> int:
68
+ return len(self.__env)
69
+
70
+ def __len__(self) -> int:
71
+ return len(self.__env)
72
+
73
+ def __iter__(self) -> Iterator[Tuple[str, Any]]:
74
+ return iter(self.__env.items())
75
+
76
+ def to_dict(self) -> Dict[str, Any]:
77
+ """ `dict`: Returns a dictionary of the parsed values. """
78
+ return self.__env
79
+
80
+ def get(self, key: str, default: Any = None) -> Any:
81
+ """ `Any`: Return the value for key if key is in the dictionary, else default. """
82
+ return self.__env.get(key, default)
83
+
84
+ @property
85
+ def keys(self) -> List[str]:
86
+ """ `list[str]`: Returns a list of the keys. """
87
+ return list(self.__env.keys())
88
+
89
+ @property
90
+ def values(self) -> List[Any]:
91
+ """ `list[Any]`: Returns a list of the values. """
92
+ return list(self.__env.values())
93
+
94
+ def items(self) -> List[Tuple[str, Any]]:
95
+ """ `list[tuple[str, Any]]`: Returns a list of the key-value pairs. """
96
+ return list(self.__env.items())
97
+
98
+ def copy(self) -> Dict[str, Any]:
99
+ """ `dict[str, Any]`: Returns a shallow copy of the parsed values. """
100
+ return self.__env.copy()
101
+
102
+ def __parser(self) -> None:
103
+ """
104
+ Parse the .env file and store the values in a dictionary.
105
+ The keys are accessible later by using the square bracket notation
106
+ directly on the DotEnv object.
107
+
108
+ Raises
109
+ ------
110
+ `FileNotFoundError`
111
+ If the file_path is not a valid path.
112
+ `ParsingError`
113
+ If one of the values cannot be parsed.
114
+ """
115
+ with open(self.__path, "r", encoding="utf-8") as f:
116
+ data: List[str] = f.readlines()
117
+
118
+ for line in data:
119
+ line = line.strip()
120
+
121
+ if line.startswith("#") or line == "":
122
+ # Ignore comment or empty line
123
+ continue
124
+
125
+ _find_kv = self.__re_keyvar.search(line)
126
+ if not _find_kv:
127
+ raise ParsingError(f"Expected key=value format, got '{line}'")
128
+
129
+ key, value = _find_kv.groups()
130
+ _force_string = False
131
+
132
+ # Replace any variables in the value
133
+ value = self.__re_var_call.sub(
134
+ lambda m: str(self.__env.get(m.group(1), "undefined")),
135
+ str(value)
136
+ )
137
+
138
+ # Remove quotes, but mark it as forced string from now
139
+ if (
140
+ value.startswith(self.__quotes) and
141
+ value.endswith(self.__quotes)
142
+ ):
143
+ value = value[1:-1]
144
+ _force_string = True
145
+
146
+ if not _force_string:
147
+
148
+ if self.__re_isdigit.search(value):
149
+ value = int(value)
150
+
151
+ elif self.__re_isfloat.search(value):
152
+ value = float(value)
153
+
154
+ elif value.lower() in ("true", "false"):
155
+ value = value.lower() == "true"
156
+
157
+ elif value.lower() in ("null", "none", "nil", "undefined"):
158
+ value = None
159
+
160
+ else:
161
+ value = value
162
+
163
+ self.__env[key] = value
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 AlexFlipnote
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.1
2
+ Name: dotenvplus
3
+ Version: 0.0.1
4
+ Summary: Python library that handles interactions from Discord POST requests.
5
+ Author-email: AlexFlipnote <root@alexflipnote.dev>
6
+ License: MIT
7
+ Keywords: discord,http,api,interaction,quart,webhook,slash
8
+ Requires-Python: >=3.6.0
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: dev
12
+ Requires-Dist: pyright; extra == "dev"
13
+ Requires-Dist: flake8; extra == "dev"
14
+ Requires-Dist: toml; extra == "dev"
15
+ Provides-Extra: maintainer
16
+ Requires-Dist: twine; extra == "maintainer"
17
+ Requires-Dist: wheel; extra == "maintainer"
18
+ Requires-Dist: build; extra == "maintainer"
19
+
20
+ # dotenvplus
21
+ Reads key-value pairs from a .env file and supports multiple values with dynamic interpolation.
22
+
23
+ The values returned by the DotEnv object is treated like a dictionary, so you can use it like a normal dictionary.
24
+ Some of the usual dictionary methods are also supported like `.items()`, `.keys()`, `.values()`, etc.
25
+
26
+ Goal is to make it easy to use environment variables in your code, while also supporting multiple values.
27
+
28
+ ## Installing
29
+ > You need **Python >=3.6** to use this library.
30
+
31
+ ```bash
32
+ pip install dotenvplus
33
+ ```
34
+
35
+ ## Usage
36
+ ```env
37
+ # .env
38
+
39
+ KEY=value
40
+ ```
41
+
42
+ ```python
43
+ # main.py
44
+
45
+ from dotenvplus import DotEnv
46
+
47
+ # Create a DotEnv object
48
+ env = DotEnv()
49
+
50
+ Call it like a dictionary
51
+ env["KEY"]
52
+ >>> "value"
53
+ ```
@@ -0,0 +1,6 @@
1
+ dotenvplus/__init__.py,sha256=Y_PFwwC8uFPpXussHQWeiect1TY6eJ0zxY1cuRnfEyM,5097
2
+ dotenvplus-0.0.1.dist-info/LICENSE,sha256=puF1l3bvJfFbnSlkpuOs1MtXnD9P7CdebKSdOmPc7Fo,1090
3
+ dotenvplus-0.0.1.dist-info/METADATA,sha256=ZUGdvmVzZTXvKm2-Lxp3qU2i2c6-F_4nGm9Q4hW8GeM,1408
4
+ dotenvplus-0.0.1.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
5
+ dotenvplus-0.0.1.dist-info/top_level.txt,sha256=nO-n31rieDIPggQ4AW2MZB9_xgdwWPwoAUUrJE7hsLI,11
6
+ dotenvplus-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ dotenvplus