envparse2 1.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.
envparse2/__init__.py ADDED
@@ -0,0 +1,237 @@
1
+ """
2
+ envparse is a simple utility to parse environment variables.
3
+ """
4
+
5
+ from __future__ import unicode_literals
6
+ import inspect
7
+ import json as pyjson
8
+ import logging
9
+ import os
10
+ import re
11
+ import shlex
12
+ import warnings
13
+ import urllib.parse as urlparse
14
+
15
+
16
+ logger = logging.getLogger(__file__)
17
+
18
+
19
+ class ConfigurationError(Exception):
20
+ pass
21
+
22
+
23
+ # Cannot rely on None since it may be desired as a return value.
24
+ NOTSET = object()
25
+
26
+
27
+ def shortcut(cast):
28
+ def method(self, var, **kwargs):
29
+ return self.__call__(var, cast=cast, **kwargs)
30
+
31
+ return method
32
+
33
+
34
+ class Env(object):
35
+ """
36
+ Lookup and cast environment variables with optional schema.
37
+
38
+ Usage:::
39
+
40
+ env = Env()
41
+ env('foo')
42
+ env.bool('bar')
43
+
44
+ # Create env with a schema
45
+ env = Env(MAIL_ENABLED=bool, SMTP_LOGIN=(str, 'DEFAULT'))
46
+ if env('MAIL_ENABLED'):
47
+ ...
48
+ """
49
+
50
+ BOOLEAN_TRUE_STRINGS = ("true", "on", "ok", "y", "yes", "1")
51
+
52
+ def __init__(self, **schema):
53
+ self.schema = schema
54
+
55
+ def __call__(
56
+ self,
57
+ var,
58
+ default=NOTSET,
59
+ cast=None,
60
+ subcast=None,
61
+ force=False,
62
+ preprocessor=None,
63
+ postprocessor=None,
64
+ ):
65
+ """
66
+ Return value for given environment variable.
67
+
68
+ :param var: Name of variable.
69
+ :param default: If var not present in environ, return this instead.
70
+ :param cast: Type or callable to cast return value as.
71
+ :param subcast: Subtype or callable to cast return values as (used for
72
+ nested structures).
73
+ :param force: force to cast to type even if default is set.
74
+ :param preprocessor: callable to run on pre-casted value.
75
+ :param postprocessor: callable to run on casted value.
76
+
77
+ :returns: Value from environment or default (if set).
78
+ """
79
+ logger.debug(
80
+ "Get '%s' casted as '%s'/'%s' with default '%s'",
81
+ var,
82
+ cast,
83
+ subcast,
84
+ default,
85
+ )
86
+
87
+ if var in self.schema:
88
+ params = self.schema[var]
89
+ if isinstance(params, dict):
90
+ if cast is None:
91
+ cast = params.get("cast", cast)
92
+ if subcast is None:
93
+ subcast = params.get("subcast", subcast)
94
+ if default is NOTSET:
95
+ default = params.get("default", default)
96
+ else:
97
+ if cast is None:
98
+ cast = params
99
+ # Default cast is `str` if it is not specified. Most types will be
100
+ # implicitly strings so reduces having to specify.
101
+ cast = str if cast is None else cast
102
+
103
+ try:
104
+ value = os.environ[var]
105
+ except KeyError:
106
+ if default is NOTSET:
107
+ error_msg = "Environment variable '{}' not set.".format(var)
108
+ raise ConfigurationError(error_msg)
109
+ else:
110
+ value = default
111
+
112
+ # Resolve any proxied values
113
+ if hasattr(value, "startswith") and value.startswith("{{"):
114
+ value = self.__call__(
115
+ value.lstrip("{{}}"),
116
+ default,
117
+ cast,
118
+ subcast,
119
+ default,
120
+ force,
121
+ preprocessor,
122
+ postprocessor,
123
+ )
124
+
125
+ if preprocessor:
126
+ value = preprocessor(value)
127
+ if value != default or force:
128
+ value = self.cast(value, cast, subcast)
129
+ if postprocessor:
130
+ value = postprocessor(value)
131
+ return value
132
+
133
+ @classmethod
134
+ def cast(cls, value, cast=str, subcast=None):
135
+ """
136
+ Parse and cast provided value.
137
+
138
+ :param value: Stringed value.
139
+ :param cast: Type or callable to cast return value as.
140
+ :param subcast: Subtype or callable to cast return values as (used for
141
+ nested structures).
142
+
143
+ :returns: Value of type `cast`.
144
+ """
145
+ if cast is bool:
146
+ value = value.lower() in cls.BOOLEAN_TRUE_STRINGS
147
+ elif cast is float:
148
+ # Clean string
149
+ float_str = re.sub(r"[^\d,\.]", "", value)
150
+ # Split to handle thousand separator for different locales, i.e.
151
+ # comma or dot being the placeholder.
152
+ parts = re.split(r"[,\.]", float_str)
153
+ if len(parts) == 1:
154
+ float_str = parts[0]
155
+ else:
156
+ float_str = "{0}.{1}".format("".join(parts[0:-1]), parts[-1])
157
+ value = float(float_str)
158
+ elif type(cast) is type and (issubclass(cast, list) or issubclass(cast, tuple)):
159
+ value = (
160
+ subcast(i.strip()) if subcast else i.strip()
161
+ for i in value.split(",")
162
+ if i
163
+ )
164
+ elif cast is dict:
165
+ value = {
166
+ k.strip(): subcast(v.strip()) if subcast else v.strip()
167
+ for k, v in (i.split("=") for i in value.split(",") if value)
168
+ }
169
+ try:
170
+ return cast(value)
171
+ except ValueError as error:
172
+ raise ConfigurationError(*error.args)
173
+
174
+ # Shortcuts
175
+ bool = shortcut(bool)
176
+ dict = shortcut(dict)
177
+ float = shortcut(float)
178
+ int = shortcut(int)
179
+ list = shortcut(list)
180
+ set = shortcut(set)
181
+ str = shortcut(str)
182
+ tuple = shortcut(tuple)
183
+ json = shortcut(pyjson.loads)
184
+ url = shortcut(urlparse.urlparse)
185
+
186
+ @staticmethod
187
+ def read_envfile(path=None, **overrides):
188
+ """
189
+ Read a .env file (line delimited KEY=VALUE) into os.environ.
190
+
191
+ If not given a path to the file, recurses up the directory tree until
192
+ found.
193
+
194
+ Uses code from Honcho (github.com/nickstenning/honcho) for parsing the
195
+ file.
196
+ """
197
+ if path is None:
198
+ frame = inspect.currentframe().f_back
199
+ caller_dir = os.path.dirname(frame.f_code.co_filename)
200
+ path = os.path.join(os.path.abspath(caller_dir), ".env")
201
+
202
+ try:
203
+ with open(path, "r") as f:
204
+ content = f.read()
205
+ except getattr(__builtins__, "FileNotFoundError", IOError):
206
+ logger.debug("envfile not found at %s, looking in parent dir.", path)
207
+ filedir, filename = os.path.split(path)
208
+ pardir = os.path.abspath(os.path.join(filedir, os.pardir))
209
+ path = os.path.join(pardir, filename)
210
+ if filedir != pardir:
211
+ Env.read_envfile(path, **overrides)
212
+ else:
213
+ # Reached top level directory.
214
+ warnings.warn("Could not any envfile.")
215
+ return
216
+
217
+ logger.debug("Reading environment variables from: %s", path)
218
+ for line in content.splitlines():
219
+ tokens = list(shlex.shlex(line, posix=True))
220
+ # parses the assignment statement
221
+ if len(tokens) < 3:
222
+ continue
223
+ name, op = tokens[:2]
224
+ value = "".join(tokens[2:])
225
+ if op != "=":
226
+ continue
227
+ if not re.match(r"[A-Za-z_][A-Za-z_0-9]*", name):
228
+ continue
229
+ value = value.replace(r"\n", "\n").replace(r"\t", "\t")
230
+ os.environ.setdefault(name, value)
231
+
232
+ for name, value in overrides.items():
233
+ os.environ.setdefault(name, value)
234
+
235
+
236
+ # Convenience object if no schema is required.
237
+ env = Env()
@@ -0,0 +1,196 @@
1
+ Metadata-Version: 2.5
2
+ Name: envparse2
3
+ Version: 1.0.1
4
+ Summary: Simple environment variable parsing
5
+ Project-URL: Repository, https://github.com/beregond/envparse2
6
+ Author-email: Rick Harris <rconradharris@gmail.com>
7
+ Maintainer-email: Szczepan Cieślik <szczepan.cieslik@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/x-rst
17
+
18
+ envparse2
19
+ =========
20
+
21
+ ``envparse2`` is a simple utility to parse environment variables.
22
+
23
+ NOTE: `envparse2` is a fork of `envparse` which is no longer maintained, to check
24
+ original author and code visit <https://github.com/rconradharris/envparse.git>
25
+
26
+ If you use Heroku and/or subscribe to the tenets of the
27
+ `12 Factor App <http://www.12factor.net/>`_
28
+ you'll be using a lot of environment variable-based configuration in your app.
29
+ ``os.environ`` is a great choice to start off with but over time you'll find
30
+ yourself duplicating quite a bit of code around handling raw environment
31
+ variables.
32
+
33
+ ``envparse2`` aims to eliminate this duplicated, often inconsistent parsing
34
+ code and instead provide a single, easy-to-use wrapper.
35
+
36
+ Ideas, and code portions, have been taken from `django-environ
37
+ <https://github.com/joke2k/django-environ>`_ project but made framework
38
+ agnostic.
39
+
40
+
41
+ Installing
42
+ ----------
43
+ Through PyPI::
44
+
45
+ $ pip install envparse2
46
+
47
+ Usage
48
+ -----
49
+ In your settings or configuration module, first either import the standard
50
+ parser or one with a schema:
51
+
52
+ .. code-block:: python
53
+
54
+ # Standard
55
+ from envparse2 import env
56
+
57
+ # Schema
58
+ from envparse2 import Env
59
+ env = Env(BOOLEAN_VAR=bool, LIST_VAR=dict(cast=list, subcast=int))
60
+
61
+
62
+ ``env`` can then be called in two ways:
63
+
64
+ * Type explicit: ``env('ENV_VAR_NAME', cast=TYPE, ...)``
65
+ * Type implicit (for Python builtin types only): ``env.TYPE('ENV_VAR_NAME', ...)``
66
+ If type is not specified, explicitly or implicitly, then the default
67
+ type is ``str``.
68
+
69
+
70
+ Casting to a specified type:
71
+
72
+ .. code-block:: python
73
+
74
+ # Environment variable: MAIL_ENABLED=1
75
+
76
+ mail_enabled = env('MAIL_ENABLED', cast=bool)
77
+ # OR mail_enabled = env.bool('MAIL_ENABLED')
78
+ assert mail_enabled is True
79
+
80
+ Casting nested types:
81
+
82
+ .. code-block:: python
83
+
84
+ # Environment variable: FOO=1,2,3
85
+ foo = env('FOO'), subcast=int)
86
+ # OR: foo = env('FOO', cast=list, subcast=int)
87
+ # Note that there is no way to implicitly call subcast.
88
+ assert foo == [1, 2, 3]
89
+
90
+ Specifying defaults:
91
+
92
+ .. code-block:: python
93
+
94
+ # Environment variable MAX_ROWS has not been defined
95
+
96
+ max_rows = env.int('MAX_ROWS', default=100)
97
+ assert max_rows == 100
98
+
99
+ Proxying values, useful in Heroku for wiring up the environment variables they
100
+ provide to the ones that your app actually uses:
101
+
102
+ .. code-block:: python
103
+
104
+ # Environment variables: MAILGUN_SMTP_LOGIN=foo,
105
+ # SMTP_LOGIN='{{MAILGUN_SMTP_LOGIN}}'
106
+
107
+ smtp_login = env('SMTP_LOGIN')
108
+ assert smtp_login == 'foo'
109
+
110
+ Now if you switch to using Mandrill as an email provider, instead of having to
111
+ modify your app, you can simply make a configuration change:
112
+
113
+ .. code-block:: bash
114
+
115
+ SMTP_LOGIN='{{MANDRILL_UESRNAME}}'
116
+
117
+ There are also a few convenience methods:
118
+
119
+ * ``env.json``: parses JSON and returns a dict.
120
+ * ``env.url``: parses a url and returns a ``urlparse.ParseResult`` object.
121
+
122
+
123
+ Type specific notes:
124
+
125
+ * list: the expected environment variable format is ``FOO=1,2,3`` and may
126
+ contain spaces between the commas as well as preceding or trailing whitespace.
127
+ * dict: the expected environment variable format is ``FOO='key1=val1,
128
+ key2=val2``. Spaces are also allowed.
129
+ * json: a regular JSON string such as ``FOO='{"foo": "bar"}'`` is expected.
130
+
131
+
132
+ Schemas
133
+ ~~~~~~~
134
+ Define a schema so you can only need to provide the cast, subcast, and defaults
135
+ once:
136
+
137
+ .. code-block:: python
138
+
139
+ # Environment variables: MAIL_ENABLED=0, LIST_INT='1,2,3'
140
+
141
+ # Bind schema to Env object to get schema-based lookups
142
+ env = Env(MAIL_ENABLED=bool, SMTP_LOGIN=dict(cast=str, default='foo'),
143
+ LIST_INT=dict(cast=list, subcast=int))
144
+ assert env('MAIL_ENABLED') is False
145
+ assert env('SMTP_LOGIN') == 'foo' # Not defined so uses default
146
+ assert env('LIST_INT') == [1, 2, 3]
147
+
148
+ The ``Env`` constructor takes values in the form of either: ``VAR_NAME=type``
149
+ or ``VAR_NAME=dict`` where ``dict`` is a dictionary with either one or more of
150
+ the following keys specified: ``cast``, ``subcast``, ``default``.
151
+
152
+
153
+ Pre- and Postprocessors
154
+ ~~~~~~~~~~~~~~~~~~~~~~~
155
+ Preprocessors are callables that are run on the environment variable string
156
+ before any type casting takes place:
157
+
158
+ .. code-block:: python
159
+
160
+ # Environment variables: FOO=bar
161
+
162
+ # Preprocessor to change variable to uppercase
163
+ to_upper = lambda v: v.upper()
164
+ foo = env('FOO', preprocessor=to_upper)
165
+ assert foo == 'BAR'
166
+
167
+ Postprocessors are callables that are run after the type casting takes place.
168
+ An example of one might be returning a datastructure expected by a framework:
169
+
170
+ .. code-block:: python
171
+
172
+ # Environment variable: REDIS_URL='redis://:redispass@127.0.0.1:6379/0'
173
+ def django_redis(url):
174
+ return {'BACKEND': 'django_redis.cache.RedisCache',
175
+ 'LOCATION': '{}:{}:{}'.format(url.hostname, url.port, url.path.strip('/')),
176
+ 'OPTIONS': {'PASSWORD': url.password}}
177
+
178
+ redis_config = env('REDIS_URL', postprocessor=django_redis)
179
+ assert redis_config == {'BACKEND': 'django_redis.cache.RedisCache',
180
+ 'LOCATION': '127.0.0.1:6379:0', 'OPTIONS': {'PASSWORD': 'redispass'}}
181
+
182
+
183
+ Environment File
184
+ ~~~~~~~~~~~~~~~~
185
+ Read from a .env file (line delimited KEY=VALUE):
186
+
187
+ .. code-block:: python
188
+
189
+ # This recurses up the directory tree until a file called '.env' is found.
190
+ env.read_envfile()
191
+
192
+ # Manually specifying a path
193
+ env.read_envfile('/config/.myenv')
194
+
195
+ # Values can be read as normal
196
+ env.int('FOO')
@@ -0,0 +1,5 @@
1
+ envparse2/__init__.py,sha256=ZTfOg3muqBDsSH7xeGU4vynCVYaiOnwWiZlS98d_Glg,7380
2
+ envparse2-1.0.1.dist-info/METADATA,sha256=RGu-9Q9p4DJw0MJWc0t3y_6w0ijf_uD2qSMfA3iK18g,6041
3
+ envparse2-1.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ envparse2-1.0.1.dist-info/licenses/LICENSE,sha256=IvB84AMFOD3YztivN4sBntdAJrZdupIkULFsZUh0esM,1162
5
+ envparse2-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Rick Harris
2
+ Copyright (c) 2013 Daniele Faraglia
3
+ Copyright (c) 2015 Russell Davies
4
+ Copyright (c) 2024 Szczepan Cieślik
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to
8
+ deal in the Software without restriction, including without limitation the
9
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10
+ sell copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in
14
+ all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22
+ IN THE SOFTWARE.