envparse2 0.3.0__tar.gz → 1.0.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,29 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "*"
7
+
8
+ jobs:
9
+ pypi-publish:
10
+ name: upload release to PyPI
11
+ runs-on: ubuntu-latest
12
+ environment: release
13
+ permissions:
14
+ id-token: write
15
+ steps:
16
+ - uses: actions/checkout@v3
17
+
18
+ - uses: actions/setup-python@v4
19
+ with:
20
+ python-version: "3.x"
21
+
22
+ - name: deps
23
+ run: python -m pip install -U build
24
+
25
+ - name: build
26
+ run: python -m build
27
+
28
+ - name: Publish package distributions to PyPI
29
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,51 @@
1
+ name: Test
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ test:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ max-parallel: 7
10
+ matrix:
11
+ python-version:
12
+ [
13
+ "pypy-3.9",
14
+ "pypy-3.10",
15
+ "pypy-3.11",
16
+ "3.9",
17
+ "3.10",
18
+ "3.11",
19
+ "3.12",
20
+ "3.13",
21
+ ]
22
+
23
+ steps:
24
+ - uses: actions/checkout@v3
25
+
26
+ - name: Set up Python ${{ matrix.python-version }}
27
+ uses: actions/setup-python@v4
28
+ with:
29
+ python-version: ${{ matrix.python-version }}
30
+
31
+ - name: Get pip cache dir
32
+ id: pip-cache
33
+ run: |
34
+ echo "::set-output name=dir::$(pip cache dir)"
35
+
36
+ - name: Cache
37
+ uses: actions/cache@v3
38
+ with:
39
+ path: ${{ steps.pip-cache.outputs.dir }}
40
+ key: ${{ matrix.os }}-${{ matrix.python-version }}-v1-${{ hashFiles('**/requirements.txt') }}
41
+ restore-keys: |
42
+ ${{ matrix.os }}-${{ matrix.python-version }}-v1-
43
+
44
+ - name: Install pytest
45
+ run: |
46
+ python -m pip install --upgrade pip
47
+ python -m pip install pytest
48
+
49
+ - name: Tests
50
+ run: |
51
+ pytest
@@ -0,0 +1,16 @@
1
+ *.py[cod]
2
+ __pycache__
3
+
4
+ build
5
+ dist
6
+ *.egg-info
7
+ .tox
8
+ .cache
9
+ .eggs
10
+ *.whl
11
+
12
+ src/envparse2/_version.py
13
+
14
+ # coverage
15
+ .coverage
16
+ htmlcov
@@ -0,0 +1,29 @@
1
+ CHANGELOG
2
+ =========
3
+
4
+ 1.0.0
5
+ -----
6
+
7
+ - Dropped support for Python 3.8 and added for 3.13 and pypy-3.11.
8
+ - Modernized packages (use pyproject.toml and hatchling).
9
+
10
+ 0.3.0
11
+ -----
12
+
13
+ - Repackaged as `envparse2` to be able to install on newer versions of Python.
14
+
15
+
16
+ v0.2.0
17
+ ------
18
+
19
+ - Major rewrite, based on django-environ but made agnostic.
20
+ - Tox support for running tests with different Python types.
21
+ - Use pytest for unit tests.
22
+
23
+
24
+ v0.1.6
25
+ ------
26
+
27
+ - Use curly-braces for proxied values since shells will attempt to resolve
28
+ dollar-sign values themselves. Dollar-sign style is still supported, but
29
+ deprecated and will be removed in a 1.0 release.
@@ -1,15 +1,18 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: envparse2
3
- Version: 0.3.0
3
+ Version: 1.0.0
4
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
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
12
9
  License-File: LICENSE
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Description-Content-Type: text/x-rst
13
16
 
14
17
  envparse2
15
18
  =========
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["hatchling", "versioningit"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ description = "Simple environment variable parsing"
7
+ name = "envparse2"
8
+ license = "MIT"
9
+ dynamic = ["version"]
10
+ readme = "README.rst"
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3.9",
13
+ "Programming Language :: Python :: 3.10",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ ]
18
+ authors = [{ name = "Rick Harris", email = "rconradharris@gmail.com" }]
19
+ maintainers = [
20
+ { name = "Szczepan Cieślik", email = "szczepan.cieslik@gmail.com" },
21
+ ]
22
+
23
+ [project.urls]
24
+ Repository = "https://github.com/beregond/envparse2"
25
+
26
+ [tool.hatch.version]
27
+ source = "versioningit"
28
+
29
+ [tool.versioningit]
30
+ default-version = "0.0.0"
31
+
32
+ [tool.versioningit.write]
33
+ file = "src/envparse2/_version.py"
@@ -1,6 +1,7 @@
1
1
  """
2
2
  envparse is a simple utility to parse environment variables.
3
3
  """
4
+
4
5
  from __future__ import unicode_literals
5
6
  import inspect
6
7
  import json as pyjson
@@ -12,9 +13,6 @@ import warnings
12
13
  import urllib.parse as urlparse
13
14
 
14
15
 
15
- __version__ = '0.3.0'
16
-
17
-
18
16
  logger = logging.getLogger(__file__)
19
17
 
20
18
 
@@ -23,12 +21,13 @@ class ConfigurationError(Exception):
23
21
 
24
22
 
25
23
  # Cannot rely on None since it may be desired as a return value.
26
- NOTSET = type(str('NoValue'), (object,), {})
24
+ NOTSET = object()
27
25
 
28
26
 
29
27
  def shortcut(cast):
30
28
  def method(self, var, **kwargs):
31
29
  return self.__call__(var, cast=cast, **kwargs)
30
+
32
31
  return method
33
32
 
34
33
 
@@ -47,13 +46,22 @@ class Env(object):
47
46
  if env('MAIL_ENABLED'):
48
47
  ...
49
48
  """
50
- BOOLEAN_TRUE_STRINGS = ('true', 'on', 'ok', 'y', 'yes', '1')
49
+
50
+ BOOLEAN_TRUE_STRINGS = ("true", "on", "ok", "y", "yes", "1")
51
51
 
52
52
  def __init__(self, **schema):
53
53
  self.schema = schema
54
54
 
55
- def __call__(self, var, default=NOTSET, cast=None, subcast=None,
56
- force=False, preprocessor=None, postprocessor=None):
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
+ ):
57
65
  """
58
66
  Return value for given environment variable.
59
67
 
@@ -68,18 +76,23 @@ class Env(object):
68
76
 
69
77
  :returns: Value from environment or default (if set).
70
78
  """
71
- logger.debug("Get '%s' casted as '%s'/'%s' with default '%s'", var,
72
- cast, subcast, default)
79
+ logger.debug(
80
+ "Get '%s' casted as '%s'/'%s' with default '%s'",
81
+ var,
82
+ cast,
83
+ subcast,
84
+ default,
85
+ )
73
86
 
74
87
  if var in self.schema:
75
88
  params = self.schema[var]
76
89
  if isinstance(params, dict):
77
90
  if cast is None:
78
- cast = params.get('cast', cast)
91
+ cast = params.get("cast", cast)
79
92
  if subcast is None:
80
- subcast = params.get('subcast', subcast)
81
- if default == NOTSET:
82
- default = params.get('default', default)
93
+ subcast = params.get("subcast", subcast)
94
+ if default is NOTSET:
95
+ default = params.get("default", default)
83
96
  else:
84
97
  if cast is None:
85
98
  cast = params
@@ -97,9 +110,17 @@ class Env(object):
97
110
  value = default
98
111
 
99
112
  # 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)
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
+ )
103
124
 
104
125
  if preprocessor:
105
126
  value = preprocessor(value)
@@ -125,23 +146,26 @@ class Env(object):
125
146
  value = value.lower() in cls.BOOLEAN_TRUE_STRINGS
126
147
  elif cast is float:
127
148
  # Clean string
128
- float_str = re.sub(r'[^\d,\.]', '', value)
149
+ float_str = re.sub(r"[^\d,\.]", "", value)
129
150
  # Split to handle thousand separator for different locales, i.e.
130
151
  # comma or dot being the placeholder.
131
- parts = re.split(r'[,\.]', float_str)
152
+ parts = re.split(r"[,\.]", float_str)
132
153
  if len(parts) == 1:
133
154
  float_str = parts[0]
134
155
  else:
135
- float_str = "{0}.{1}".format(''.join(parts[0:-1]), parts[-1])
156
+ float_str = "{0}.{1}".format("".join(parts[0:-1]), parts[-1])
136
157
  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)
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
+ )
141
164
  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)}
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
+ }
145
169
  try:
146
170
  return cast(value)
147
171
  except ValueError as error:
@@ -173,14 +197,13 @@ class Env(object):
173
197
  if path is None:
174
198
  frame = inspect.currentframe().f_back
175
199
  caller_dir = os.path.dirname(frame.f_code.co_filename)
176
- path = os.path.join(os.path.abspath(caller_dir), '.env')
200
+ path = os.path.join(os.path.abspath(caller_dir), ".env")
177
201
 
178
202
  try:
179
- with open(path, 'r') as f:
203
+ with open(path, "r") as f:
180
204
  content = f.read()
181
- except getattr(__builtins__, 'FileNotFoundError', IOError):
182
- logger.debug('envfile not found at %s, looking in parent dir.',
183
- path)
205
+ except getattr(__builtins__, "FileNotFoundError", IOError):
206
+ logger.debug("envfile not found at %s, looking in parent dir.", path)
184
207
  filedir, filename = os.path.split(path)
185
208
  pardir = os.path.abspath(os.path.join(filedir, os.pardir))
186
209
  path = os.path.join(pardir, filename)
@@ -188,26 +211,27 @@ class Env(object):
188
211
  Env.read_envfile(path, **overrides)
189
212
  else:
190
213
  # Reached top level directory.
191
- warnings.warn('Could not any envfile.')
214
+ warnings.warn("Could not any envfile.")
192
215
  return
193
216
 
194
- logger.debug('Reading environment variables from: %s', path)
217
+ logger.debug("Reading environment variables from: %s", path)
195
218
  for line in content.splitlines():
196
219
  tokens = list(shlex.shlex(line, posix=True))
197
220
  # parses the assignment statement
198
221
  if len(tokens) < 3:
199
222
  continue
200
223
  name, op = tokens[:2]
201
- value = ''.join(tokens[2:])
202
- if op != '=':
224
+ value = "".join(tokens[2:])
225
+ if op != "=":
203
226
  continue
204
- if not re.match(r'[A-Za-z_][A-Za-z_0-9]*', name):
227
+ if not re.match(r"[A-Za-z_][A-Za-z_0-9]*", name):
205
228
  continue
206
- value = value.replace(r'\n', '\n').replace(r'\t', '\t')
229
+ value = value.replace(r"\n", "\n").replace(r"\t", "\t")
207
230
  os.environ.setdefault(name, value)
208
231
 
209
232
  for name, value in overrides.items():
210
233
  os.environ.setdefault(name, value)
211
234
 
235
+
212
236
  # Convenience object if no schema is required.
213
237
  env = Env()
File without changes
@@ -0,0 +1,15 @@
1
+ BLANK=''
2
+ STR=foo
3
+ INT=42
4
+ FLOAT=33.3
5
+ BOOL_TRUE=1
6
+ BOOL_FALSE=0
7
+ PROXIED={{STR}}
8
+ LIST_STR='foo,bar'
9
+ LIST_STR_WITH_SPACES=' foo, bar'
10
+ LIST_INT=1,2,3
11
+ LIST_INT_WITH_SPACES=1, 2,3
12
+ DICT_STR=key1=val1, key2=val2
13
+ DICT_INT=key1=1, key2=2
14
+ JSON='{"foo": "bar", "baz": [1, 2, 3]}'
15
+ URL=https://example.com/path?query=1
@@ -0,0 +1,162 @@
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("src/tests/envfile")
33
+
34
+
35
+ # Helper function
36
+ def assert_type_value(cast, expected, result):
37
+ assert issubclass(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, subcast=int))
89
+ assert_type_value(list, list_int, env.list("LIST_INT", subcast=int))
90
+ assert_type_value(list, list_int, env.list("LIST_INT_WITH_SPACES", subcast=int))
91
+ assert_type_value(list, [], env.list("BLANK", subcast=int))
92
+
93
+
94
+ def test_dict():
95
+ dict_str = dict(key1="val1", key2="val2")
96
+ assert_type_value(dict, dict_str, env.dict("DICT_STR"))
97
+ assert_type_value(dict, dict_str, env("DICT_STR", cast=dict))
98
+ dict_int = dict(key1=1, key2=2)
99
+ assert_type_value(dict, dict_int, env("DICT_INT", cast=dict, subcast=int))
100
+ assert_type_value(dict, dict_int, env.dict("DICT_INT", subcast=int))
101
+ assert_type_value(dict, {}, env.dict("BLANK"))
102
+
103
+
104
+ def test_json():
105
+ expected = {"foo": "bar", "baz": [1, 2, 3]}
106
+ assert_type_value(dict, expected, env.json("JSON"))
107
+
108
+
109
+ def test_url():
110
+ url = urlparse.urlparse("https://example.com/path?query=1")
111
+ assert_type_value(url.__class__, url, env.url("URL"))
112
+
113
+
114
+ def proxied_value():
115
+ assert_type_value(str, "bar", env("PROXIED"))
116
+
117
+
118
+ def test_preprocessor():
119
+ assert_type_value(str, "FOO", env("STR", preprocessor=lambda v: v.upper()))
120
+
121
+
122
+ def test_postprocessor(monkeypatch):
123
+ """
124
+ Test a postprocessor which turns a redis url into a Django compatible
125
+ cache url.
126
+ """
127
+ redis_url = "redis://:redispass@127.0.0.1:6379/0"
128
+ monkeypatch.setenv("redis_url", redis_url)
129
+ expected = {
130
+ "BACKEND": "django_redis.cache.RedisCache",
131
+ "LOCATION": "127.0.0.1:6379:0",
132
+ "OPTIONS": {"PASSWORD": "redispass"},
133
+ }
134
+
135
+ def django_redis(url):
136
+ return {
137
+ "BACKEND": "django_redis.cache.RedisCache",
138
+ "LOCATION": "{}:{}:{}".format(url.hostname, url.port, url.path.strip("/")),
139
+ "OPTIONS": {"PASSWORD": url.password},
140
+ }
141
+
142
+ assert_type_value(dict, expected, env.url("redis_url", postprocessor=django_redis))
143
+
144
+
145
+ def test_schema():
146
+ env = Env(
147
+ STR=str,
148
+ STR_DEFAULT=dict(cast=str, default="default"),
149
+ INT=int,
150
+ LIST_STR=list,
151
+ LIST_INT=dict(cast=list, subcast=int),
152
+ )
153
+ assert_type_value(str, "foo", env("STR"))
154
+ assert_type_value(str, "default", env("STR_DEFAULT"))
155
+ assert_type_value(int, 42, env("INT"))
156
+ assert_type_value(list, ["foo", "bar"], env("LIST_STR"))
157
+ assert_type_value(list, [1, 2, 3], env("LIST_INT"))
158
+ # Overrides
159
+ assert_type_value(str, "42", env("INT", cast=str))
160
+ assert_type_value(
161
+ str, "manual_default", env("STR_DEFAULT", default="manual_default")
162
+ )
envparse2-0.3.0/PKG-INFO DELETED
@@ -1,192 +0,0 @@
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')
@@ -1,12 +0,0 @@
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
@@ -1 +0,0 @@
1
- envparse2
envparse2-0.3.0/setup.cfg DELETED
@@ -1,7 +0,0 @@
1
- [wheel]
2
- universal = 1
3
-
4
- [egg_info]
5
- tag_build =
6
- tag_date = 0
7
-
envparse2-0.3.0/setup.py DELETED
@@ -1,39 +0,0 @@
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
- )
@@ -1,158 +0,0 @@
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'))
File without changes
File without changes
File without changes