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