envparse2 0.3.0__tar.gz

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 @@
1
+ include README.rst LICENSE
@@ -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,179 @@
1
+ envparse2
2
+ =========
3
+
4
+ ``envparse2`` is a simple utility to parse environment variables.
5
+
6
+ NOTE: `envparse2` is a fork of `envparse` which is no longer maintained, to check
7
+ original author and code visit <https://github.com/rconradharris/envparse.git>
8
+
9
+ If you use Heroku and/or subscribe to the tenets of the
10
+ `12 Factor App <http://www.12factor.net/>`_
11
+ you'll be using a lot of environment variable-based configuration in your app.
12
+ ``os.environ`` is a great choice to start off with but over time you'll find
13
+ yourself duplicating quite a bit of code around handling raw environment
14
+ variables.
15
+
16
+ ``envparse2`` aims to eliminate this duplicated, often inconsistent parsing
17
+ code and instead provide a single, easy-to-use wrapper.
18
+
19
+ Ideas, and code portions, have been taken from `django-environ
20
+ <https://github.com/joke2k/django-environ>`_ project but made framework
21
+ agnostic.
22
+
23
+
24
+ Installing
25
+ ----------
26
+ Through PyPI::
27
+
28
+ $ pip install envparse2
29
+
30
+ Usage
31
+ -----
32
+ In your settings or configuration module, first either import the standard
33
+ parser or one with a schema:
34
+
35
+ .. code-block:: python
36
+
37
+ # Standard
38
+ from envparse2 import env
39
+
40
+ # Schema
41
+ from envparse2 import Env
42
+ env = Env(BOOLEAN_VAR=bool, LIST_VAR=dict(cast=list, subcast=int))
43
+
44
+
45
+ ``env`` can then be called in two ways:
46
+
47
+ * Type explicit: ``env('ENV_VAR_NAME', cast=TYPE, ...)``
48
+ * Type implicit (for Python builtin types only): ``env.TYPE('ENV_VAR_NAME', ...)``
49
+ If type is not specified, explicitly or implicitly, then the default
50
+ type is ``str``.
51
+
52
+
53
+ Casting to a specified type:
54
+
55
+ .. code-block:: python
56
+
57
+ # Environment variable: MAIL_ENABLED=1
58
+
59
+ mail_enabled = env('MAIL_ENABLED', cast=bool)
60
+ # OR mail_enabled = env.bool('MAIL_ENABLED')
61
+ assert mail_enabled is True
62
+
63
+ Casting nested types:
64
+
65
+ .. code-block:: python
66
+
67
+ # Environment variable: FOO=1,2,3
68
+ foo = env('FOO'), subcast=int)
69
+ # OR: foo = env('FOO', cast=list, subcast=int)
70
+ # Note that there is no way to implicitly call subcast.
71
+ assert foo == [1, 2, 3]
72
+
73
+ Specifying defaults:
74
+
75
+ .. code-block:: python
76
+
77
+ # Environment variable MAX_ROWS has not been defined
78
+
79
+ max_rows = env.int('MAX_ROWS', default=100)
80
+ assert max_rows == 100
81
+
82
+ Proxying values, useful in Heroku for wiring up the environment variables they
83
+ provide to the ones that your app actually uses:
84
+
85
+ .. code-block:: python
86
+
87
+ # Environment variables: MAILGUN_SMTP_LOGIN=foo,
88
+ # SMTP_LOGIN='{{MAILGUN_SMTP_LOGIN}}'
89
+
90
+ smtp_login = env('SMTP_LOGIN')
91
+ assert smtp_login == 'foo'
92
+
93
+ Now if you switch to using Mandrill as an email provider, instead of having to
94
+ modify your app, you can simply make a configuration change:
95
+
96
+ .. code-block:: bash
97
+
98
+ SMTP_LOGIN='{{MANDRILL_UESRNAME}}'
99
+
100
+ There are also a few convenience methods:
101
+
102
+ * ``env.json``: parses JSON and returns a dict.
103
+ * ``env.url``: parses a url and returns a ``urlparse.ParseResult`` object.
104
+
105
+
106
+ Type specific notes:
107
+
108
+ * list: the expected environment variable format is ``FOO=1,2,3`` and may
109
+ contain spaces between the commas as well as preceding or trailing whitespace.
110
+ * dict: the expected environment variable format is ``FOO='key1=val1,
111
+ key2=val2``. Spaces are also allowed.
112
+ * json: a regular JSON string such as ``FOO='{"foo": "bar"}'`` is expected.
113
+
114
+
115
+ Schemas
116
+ ~~~~~~~
117
+ Define a schema so you can only need to provide the cast, subcast, and defaults
118
+ once:
119
+
120
+ .. code-block:: python
121
+
122
+ # Environment variables: MAIL_ENABLED=0, LIST_INT='1,2,3'
123
+
124
+ # Bind schema to Env object to get schema-based lookups
125
+ env = Env(MAIL_ENABLED=bool, SMTP_LOGIN=dict(cast=str, default='foo'),
126
+ LIST_INT=dict(cast=list, subcast=int))
127
+ assert env('MAIL_ENABLED') is False
128
+ assert env('SMTP_LOGIN') == 'foo' # Not defined so uses default
129
+ assert env('LIST_INT') == [1, 2, 3]
130
+
131
+ The ``Env`` constructor takes values in the form of either: ``VAR_NAME=type``
132
+ or ``VAR_NAME=dict`` where ``dict`` is a dictionary with either one or more of
133
+ the following keys specified: ``cast``, ``subcast``, ``default``.
134
+
135
+
136
+ Pre- and Postprocessors
137
+ ~~~~~~~~~~~~~~~~~~~~~~~
138
+ Preprocessors are callables that are run on the environment variable string
139
+ before any type casting takes place:
140
+
141
+ .. code-block:: python
142
+
143
+ # Environment variables: FOO=bar
144
+
145
+ # Preprocessor to change variable to uppercase
146
+ to_upper = lambda v: v.upper()
147
+ foo = env('FOO', preprocessor=to_upper)
148
+ assert foo == 'BAR'
149
+
150
+ Postprocessors are callables that are run after the type casting takes place.
151
+ An example of one might be returning a datastructure expected by a framework:
152
+
153
+ .. code-block:: python
154
+
155
+ # Environment variable: REDIS_URL='redis://:redispass@127.0.0.1:6379/0'
156
+ def django_redis(url):
157
+ return {'BACKEND': 'django_redis.cache.RedisCache',
158
+ 'LOCATION': '{}:{}:{}'.format(url.hostname, url.port, url.path.strip('/')),
159
+ 'OPTIONS': {'PASSWORD': url.password}}
160
+
161
+ redis_config = env('REDIS_URL', postprocessor=django_redis)
162
+ assert redis_config == {'BACKEND': 'django_redis.cache.RedisCache',
163
+ 'LOCATION': '127.0.0.1:6379:0', 'OPTIONS': {'PASSWORD': 'redispass'}}
164
+
165
+
166
+ Environment File
167
+ ~~~~~~~~~~~~~~~~
168
+ Read from a .env file (line delimited KEY=VALUE):
169
+
170
+ .. code-block:: python
171
+
172
+ # This recurses up the directory tree until a file called '.env' is found.
173
+ env.read_envfile()
174
+
175
+ # Manually specifying a path
176
+ env.read_envfile('/config/.myenv')
177
+
178
+ # Values can be read as normal
179
+ env.int('FOO')
@@ -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,12 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.rst
4
+ envparse2.py
5
+ setup.cfg
6
+ setup.py
7
+ envparse2.egg-info/PKG-INFO
8
+ envparse2.egg-info/SOURCES.txt
9
+ envparse2.egg-info/dependency_links.txt
10
+ envparse2.egg-info/not-zip-safe
11
+ envparse2.egg-info/top_level.txt
12
+ tests/test_casts.py
@@ -0,0 +1 @@
1
+ envparse2
@@ -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()
@@ -0,0 +1,7 @@
1
+ [wheel]
2
+ universal = 1
3
+
4
+ [egg_info]
5
+ tag_build =
6
+ tag_date = 0
7
+
@@ -0,0 +1,39 @@
1
+ from __future__ import print_function
2
+ from setuptools import setup
3
+ import codecs
4
+ import os
5
+ import re
6
+
7
+
8
+ def read(*parts):
9
+ here = os.path.abspath(os.path.dirname(__file__))
10
+ # intentionally *not* adding an encoding option to open
11
+ return codecs.open(os.path.join(here, *parts), "r").read()
12
+
13
+
14
+ def find_version(*file_paths):
15
+ version_file = read(*file_paths)
16
+ version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
17
+ if version_match:
18
+ return version_match.group(1)
19
+ raise RuntimeError("Unable to find version string.")
20
+
21
+
22
+ setup(
23
+ name="envparse2",
24
+ version=find_version(".", "envparse2.py"),
25
+ url="https://github.com/beregond/envparse2",
26
+ license="MIT",
27
+ author="Rick Harris",
28
+ author_email="rconradharris@gmail.com",
29
+ tests_require=["pytest"],
30
+ description="Simple environment variable parsing",
31
+ long_description=read("README.rst"),
32
+ py_modules=["envparse2"],
33
+ platforms="any",
34
+ zip_safe=False,
35
+ classifiers=[
36
+ "Programming Language :: Python",
37
+ "Programming Language :: Python :: 3",
38
+ ],
39
+ )
@@ -0,0 +1,158 @@
1
+ import pytest
2
+
3
+ from envparse2 import Env, env, ConfigurationError, urlparse
4
+
5
+
6
+ env_vars = dict(
7
+ BLANK='',
8
+ STR='foo',
9
+ INT='42',
10
+ FLOAT='33.3',
11
+ BOOL_TRUE='1',
12
+ BOOL_FALSE='0',
13
+ PROXIED='{{STR}}',
14
+ LIST_STR='foo,bar',
15
+ LIST_STR_WITH_SPACES=' foo, bar',
16
+ LIST_INT='1,2,3',
17
+ LIST_INT_WITH_SPACES=' 1, 2,3',
18
+ DICT_STR='key1=val1, key2=val2',
19
+ DICT_INT='key1=1, key2=2',
20
+ JSON='{"foo": "bar", "baz": [1, 2, 3]}',
21
+ URL='https://example.com/path?query=1',
22
+ )
23
+
24
+
25
+ @pytest.fixture(autouse=True, params=['environ', 'envfile'])
26
+ def environ(monkeypatch, request):
27
+ """Setup environment with sample variables."""
28
+ if request.param == 'environ':
29
+ for key, val in env_vars.items():
30
+ monkeypatch.setenv(key, val)
31
+ elif request.param == 'envfile':
32
+ env.read_envfile('tests/envfile')
33
+
34
+
35
+ # Helper function
36
+ def assert_type_value(cast, expected, result):
37
+ assert cast == type(result)
38
+ assert expected == result
39
+
40
+
41
+ def test_var_not_present():
42
+ with pytest.raises(ConfigurationError):
43
+ env('NOT_PRESENT')
44
+
45
+
46
+ def test_var_not_present_with_default():
47
+ default_val = 'default val'
48
+ assert default_val, env('NOT_PRESENT', default=default_val)
49
+
50
+
51
+ def test_default_none():
52
+ assert_type_value(type(None), None, env('NOT_PRESENT', default=None))
53
+
54
+
55
+ def test_implicit_nonbuiltin_type():
56
+ with pytest.raises(AttributeError):
57
+ env.foo('FOO')
58
+
59
+
60
+ def test_str():
61
+ expected = str(env_vars['STR'])
62
+ assert_type_value(str, expected, env('STR'))
63
+ assert_type_value(str, expected, env.str('STR'))
64
+
65
+
66
+ def test_int():
67
+ expected = int(env_vars['INT'])
68
+ assert_type_value(int, expected, env('INT', cast=int))
69
+ assert_type_value(int, expected, env.int('INT'))
70
+
71
+
72
+ def test_float():
73
+ expected = float(env_vars['FLOAT'])
74
+ assert_type_value(float, expected, env.float('FLOAT'))
75
+
76
+
77
+ def test_bool():
78
+ assert_type_value(bool, True, env.bool('BOOL_TRUE'))
79
+ assert_type_value(bool, False, env.bool('BOOL_FALSE'))
80
+
81
+
82
+ def test_list():
83
+ list_str = ['foo', 'bar']
84
+ assert_type_value(list, list_str, env('LIST_STR', cast=list))
85
+ assert_type_value(list, list_str, env.list('LIST_STR'))
86
+ assert_type_value(list, list_str, env.list('LIST_STR_WITH_SPACES'))
87
+ list_int = [1, 2, 3]
88
+ assert_type_value(list, list_int, env('LIST_INT', cast=list,
89
+ subcast=int))
90
+ assert_type_value(list, list_int, env.list('LIST_INT', subcast=int))
91
+ assert_type_value(list, list_int, env.list('LIST_INT_WITH_SPACES',
92
+ subcast=int))
93
+ assert_type_value(list, [], env.list('BLANK', subcast=int))
94
+
95
+
96
+ def test_dict():
97
+ dict_str = dict(key1='val1', key2='val2')
98
+ assert_type_value(dict, dict_str, env.dict('DICT_STR'))
99
+ assert_type_value(dict, dict_str, env('DICT_STR', cast=dict))
100
+ dict_int = dict(key1=1, key2=2)
101
+ assert_type_value(dict, dict_int, env('DICT_INT', cast=dict,
102
+ subcast=int))
103
+ assert_type_value(dict, dict_int, env.dict('DICT_INT', subcast=int))
104
+ assert_type_value(dict, {}, env.dict('BLANK'))
105
+
106
+
107
+ def test_json():
108
+ expected = {'foo': 'bar', 'baz': [1, 2, 3]}
109
+ assert_type_value(dict, expected, env.json('JSON'))
110
+
111
+
112
+ def test_url():
113
+ url = urlparse.urlparse('https://example.com/path?query=1')
114
+ assert_type_value(url.__class__, url, env.url('URL'))
115
+
116
+
117
+ def proxied_value():
118
+ assert_type_value(str, 'bar', env('PROXIED'))
119
+
120
+
121
+ def test_preprocessor():
122
+ assert_type_value(str, 'FOO', env('STR', preprocessor=lambda
123
+ v: v.upper()))
124
+
125
+
126
+ def test_postprocessor(monkeypatch):
127
+ """
128
+ Test a postprocessor which turns a redis url into a Django compatible
129
+ cache url.
130
+ """
131
+ redis_url = 'redis://:redispass@127.0.0.1:6379/0'
132
+ monkeypatch.setenv('redis_url', redis_url)
133
+ expected = {'BACKEND': 'django_redis.cache.RedisCache',
134
+ 'LOCATION': '127.0.0.1:6379:0',
135
+ 'OPTIONS': {'PASSWORD': 'redispass'}}
136
+
137
+ def django_redis(url):
138
+ return {
139
+ 'BACKEND': 'django_redis.cache.RedisCache',
140
+ 'LOCATION': '{}:{}:{}'.format(url.hostname, url.port, url.path.strip('/')),
141
+ 'OPTIONS': {'PASSWORD': url.password}}
142
+
143
+ assert_type_value(dict, expected, env.url('redis_url',
144
+ postprocessor=django_redis))
145
+
146
+
147
+ def test_schema():
148
+ env = Env(STR=str, STR_DEFAULT=dict(cast=str, default='default'),
149
+ INT=int, LIST_STR=list, LIST_INT=dict(cast=list, subcast=int))
150
+ assert_type_value(str, 'foo', env('STR'))
151
+ assert_type_value(str, 'default', env('STR_DEFAULT'))
152
+ assert_type_value(int, 42, env('INT'))
153
+ assert_type_value(list, ['foo', 'bar'], env('LIST_STR'))
154
+ assert_type_value(list, [1, 2, 3], env('LIST_INT'))
155
+ # Overrides
156
+ assert_type_value(str, '42', env('INT', cast=str))
157
+ assert_type_value(str, 'manual_default', env('STR_DEFAULT',
158
+ default='manual_default'))