├── .bumpversion.cfg ├── .gitignore ├── .travis.yml ├── HISTORY.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── envs ├── __init__.py ├── cli.py ├── exceptions.py ├── templates │ └── settings.jinja2 ├── test_settings.py ├── tests.py └── util.py ├── requirements_cli.txt ├── setup.py └── test-requirements.txt /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.3.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | cover/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # IPython Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # dotenv 80 | .env 81 | 82 | 83 | 84 | # Spyder project settings 85 | .spyderproject 86 | 87 | # Rope project settings 88 | .ropeproject 89 | 90 | # PyCharm Stuff 91 | .idea/ 92 | 93 | # Local test files 94 | .envs_result 95 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "2.7" 4 | - "3.4" 5 | - "3.5" 6 | - "3.6" 7 | - "3.7" 8 | - "3.8-dev" # 3.8 development branch 9 | - "nightly" # nightly build 10 | # command to install dependencies 11 | install: "pip install -r test-requirements.txt" 12 | # command to run tests, we isolate the tests since the Click CLI Runner 13 | # alters the global state 14 | script: nosetests --with-isolation 15 | -------------------------------------------------------------------------------- /HISTORY.md: -------------------------------------------------------------------------------- 1 | #Changes 2 | 3 | ## 1.2.4 4 | 5 | Added Decimals variable type 6 | 7 | ## 0.3.0 8 | Removed the need for string defaults, you can now use real objects as the default 9 | Refactored most of the code and test (still 100% coverage and no only 47 LOC) 10 | 11 | ## 0.2.0 12 | 13 | Updated test for 100% coverage 14 | Converted env from a function to a class 15 | 16 | ## 0.1.2 17 | 18 | Initial release 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.md 3 | include requirements_cli.txt 4 | 5 | recursive-include envs/ * 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # envs 2 | Easy access of environment variables from Python with support for booleans, strings, lists, tuples, integers, floats, and dicts. 3 | 4 | ## Use Case 5 | 6 | If you need environment variables for your settings but need an easy way of using Python objects instead of just strings. For example, if you need a list of strings. 7 | 8 | ## Features 9 | 10 | - CLI to convert settings 11 | - CLI to list and check environment variables 12 | - Use strings, lists, tuples, integers, floats or dicts. **IMPORTANT:** When setting the variables in your environmenet (ex. in .env file) wrap them in single or double quotes (ex. `"['some','list']"`) 13 | 14 | [![Build Status](https://travis-ci.org/capless/envs.svg?branch=master)](https://travis-ci.org/capless/envs) 15 | 16 | ## Quick Start 17 | ### Install 18 | #### Install without CLI Requirements 19 | 20 | ```commandline 21 | pip install envs 22 | ``` 23 | #### Install with CLI Requirements 24 | 25 | ```commandline 26 | pip install envs["cli"] 27 | ``` 28 | ### Run Convert Settings 29 | 30 | **IMPORTANT:** Don't name this file the same as the original module (you have added the imports back yet). 31 | ```commandline 32 | envs convert_settings --settings-file your.settings.module 33 | ``` 34 | 35 | ### Copy and Paste the Imports and Logic Code From Original File 36 | 37 | Envs does not copy and paste your imports from your original code, so you have to do this manually. 38 | 39 | ### Run List Envs 40 | 41 | This tells you what envs have default v 42 | ```commandline 43 | envs list_envs --settings-file your.settings.module 44 | ``` 45 | ## General API 46 | 47 | ```python 48 | from envs import env 49 | 50 | env('SOMEVAR','default value for that var',var_type='string',allow_none=True) 51 | ``` 52 | 53 | ### Strings 54 | 55 | **Environment Variable Example:** SECRET_KEY='adfadfadfafasf' 56 | ```python 57 | >>>from envs import env 58 | 59 | >>>env('SECRET_KEY','default secret key here') 60 | 'adfadfadfafasf' 61 | ``` 62 | 63 | ### Lists 64 | **Environment Variable Example:** SERVER_NAMES="['coastal','inland','western']" 65 | ```python 66 | >>>from envs import env 67 | 68 | >>>env('SERVER_NAMES',var_type='list') 69 | ['coastal','inland','western'] 70 | ``` 71 | 72 | ### Tuples 73 | **Environment Variable Example:** SERVER_NAMES="('coastal','inland','western')" 74 | 75 | ```python 76 | >>>from envs import env 77 | 78 | >>>env('SERVER_NAMES',var_type='tuple') 79 | ('coastal','inland','western') 80 | ``` 81 | 82 | ### Dicts 83 | **Environment Variable Example:** DATABASE="{'USER':'name','PASSWORD':'password'}" 84 | 85 | ```python 86 | >>>from envs import env 87 | 88 | >>>env('DATABASE',var_type='dict') 89 | {'USER':'name','PASSWORD':'password'} 90 | ``` 91 | 92 | ### Integers 93 | 94 | **Environment Variable Example:** NO_SERVERS=12 95 | ```python 96 | >>>from envs import env 97 | 98 | >>>env('NO_SERVERS',var_type='integer') 99 | 12 100 | ``` 101 | 102 | ### Floats 103 | 104 | **Environment Variable Example:** INDEX_WEIGHT=0.9 105 | ```python 106 | >>>from envs import env 107 | 108 | >>>env('INDEX_WEIGHT',var_type='float') 109 | 0.9 110 | ``` 111 | 112 | ### Booleans 113 | **Environment Variable Example:** USE_PROFILE=false 114 | ```python 115 | >>>from envs import env 116 | 117 | >>>env('USE_PROFILE',var_type='boolean') 118 | False 119 | ``` 120 | 121 | ### Decimals 122 | **Environment Variable Example:** HALF_SEVEN=3.5 123 | ```python 124 | >>> from envs import env 125 | 126 | >>> env('HALF_SEVEN', var_type='decimal') 127 | Decimal('3.5') 128 | ``` 129 | 130 | ## Command Line Utils 131 | 132 | **IMPORTANT:** All of the command arguments will fallback to becoming prompts if not set when calling the commands. 133 | 134 | ### Convert Module (convert_module) 135 | 136 | Converts an existing settings file so it uses envs. **IMPORTANT:** This command does not copy your **import** stataements to the new module. 137 | 138 | #### Arguments 139 | 140 | - **settings-file:** - Dot notated import string for settings file 141 | 142 | ```commandline 143 | envs convert_module --settings-file your.settings 144 | ``` 145 | 146 | ### List Envs (list_envs) 147 | 148 | Shows a list of env instances set in a settings file. 149 | 150 | - **settings-file:** - Dot notated import string for settings file 151 | - **keep-result:** - Keep the .env_results file generated by this command (**default:** False) 152 | 153 | ```commandline 154 | envs list_envs --settings-file your.settings --keep-result False 155 | ``` 156 | 157 | ### Check Envs (check_envs) 158 | 159 | Make sure that the defined envs with no default value have a value set in the environment. This command will raise an **EnvsValueException** if there is environment variable that should be set that is not. This command is meant for use with a CI/CD tool as a way to halt the build if there isn't a value for an environment variable. 160 | 161 | - **settings-file:** - Dot notated import string for settings file 162 | 163 | ```commandline 164 | envs check_envs --settings-file your.settings 165 | ``` 166 | 167 | ### Author 168 | 169 | **Twitter:**:[@brianjinwright](https://twitter.com/brianjinwright) 170 | **Github:** [bjinwright](https://github.com/bjinwright) 171 | -------------------------------------------------------------------------------- /envs/__init__.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import json 3 | import os 4 | import sys 5 | from decimal import Decimal 6 | 7 | from .exceptions import EnvsValueException 8 | 9 | _envs_list = [] 10 | 11 | class CLIArguments(): 12 | LIST_ENVS = 'list-envs' 13 | CHECK_ENVS = 'check-envs' 14 | CONVERT_SETTINGS = 'convert-settings' 15 | 16 | ARGUMENTS = CLIArguments() 17 | 18 | ENVS_RESULT_FILENAME = '.envs_result' 19 | 20 | 21 | def validate_boolean(value): 22 | true_vals = ('True', 'true', 1, '1') 23 | false_vals = ('False', 'false', 0, '0') 24 | if value in true_vals: 25 | value = True 26 | elif value in false_vals: 27 | value = False 28 | else: 29 | raise ValueError('This value is not a boolean value.') 30 | return value 31 | 32 | 33 | class Env(object): 34 | valid_types = { 35 | 'string': None, 36 | 'boolean': validate_boolean, 37 | 'list': list, 38 | 'tuple': tuple, 39 | 'integer': int, 40 | 'float': float, 41 | 'dict': dict, 42 | 'decimal': Decimal 43 | } 44 | 45 | def __call__(self, key, default=None, var_type='string', allow_none=True): 46 | if ARGUMENTS.LIST_ENVS in sys.argv or ARGUMENTS.CHECK_ENVS in sys.argv: 47 | with open(ENVS_RESULT_FILENAME, 'a') as f: 48 | json.dump({'key': key, 'var_type': var_type, 'default': default, 'value': os.getenv(key)}, f) 49 | f.write(',') 50 | value = os.getenv(key, default) 51 | if not var_type in self.valid_types.keys(): 52 | raise ValueError( 53 | 'The var_type argument should be one of the following {0}'.format( 54 | ','.join(self.valid_types.keys()))) 55 | if value is None: 56 | if not allow_none: 57 | raise EnvsValueException('{}: Environment Variable Not Set'.format(key)) 58 | return value 59 | return self.validate_type(value, self.valid_types[var_type], key) 60 | 61 | def validate_type(self, value, klass, key): 62 | if not klass: 63 | return value 64 | if klass in (validate_boolean, Decimal): 65 | return klass(value) 66 | if isinstance(value, klass): 67 | return value 68 | return klass(ast.literal_eval(value)) 69 | 70 | 71 | env = Env() 72 | -------------------------------------------------------------------------------- /envs/cli.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import click 4 | import jinja2 5 | from terminaltables import AsciiTable 6 | 7 | from envs.exceptions import EnvsValueException 8 | from . import env 9 | from . import ARGUMENTS, ENVS_RESULT_FILENAME 10 | from .util import convert_module, import_mod, list_envs_module, raw_input 11 | 12 | SETTINGS_TEMPLATE = jinja2.Environment(loader=jinja2.PackageLoader( 13 | 'envs', 'templates')).get_template('settings.jinja2') 14 | 15 | 16 | @click.group() 17 | def envs(): 18 | pass 19 | 20 | 21 | @envs.command(ARGUMENTS.CONVERT_SETTINGS, help='Converts an existing settings file so it uses envs.') 22 | @click.option('--settings-file', prompt=True, 23 | help='Settings Module? ex. settings or yourapp.settings') 24 | def convert_settings(settings_file): 25 | attr_list = convert_module(import_mod(settings_file)) 26 | template = SETTINGS_TEMPLATE.render(attr_list=attr_list) 27 | new_settings_filename = raw_input( 28 | 'What should we name this new settings file? (DO NOT NAME IT THE SAME AS THE ORIGINAL BECAUSE THERE ARE NO IMPORTS): ') 29 | if not new_settings_filename: 30 | raise ValueError('Settings filename is required.') 31 | with open(new_settings_filename, 'w+') as f: 32 | f.write(template) 33 | click.echo(click.style('Your new settings file {}'.format(new_settings_filename), fg='green')) 34 | 35 | 36 | @envs.command(ARGUMENTS.LIST_ENVS, help='Shows a list of env instances set in a settings file.') 37 | @click.option('--settings-file', prompt=True, 38 | help='Settings Module? ex. settings or yourapp.settings') 39 | @click.option('--keep-result', prompt=True, help='Keep the result file ({})?'.format(ENVS_RESULT_FILENAME), default=False) 40 | def list_envs(settings_file, keep_result): 41 | envs_result = list_envs_module(settings_file) 42 | table_data = [ 43 | ['Env Var', 'Var Type', 'Has Default', 'Environment Value'], 44 | 45 | ] 46 | table_data.extend( 47 | [[row.get('key'), row.get('var_type'), bool(row.get('default')), row.get('value')] for row in envs_result]) 48 | click.echo(AsciiTable(table_data).table) 49 | 50 | if not keep_result: 51 | os.remove(ENVS_RESULT_FILENAME) 52 | 53 | 54 | @envs.command(ARGUMENTS.CHECK_ENVS, help='Make sure that the defined envs with no default value have a value set in the environment.') 55 | @click.option('--settings-file', prompt=True, 56 | help='Settings Module? ex. settings or yourapp.settings') 57 | def check_envs(settings_file): 58 | envs_result = list_envs_module(settings_file) 59 | for row in envs_result: 60 | value = env(row.get('key'), row.get('default'), var_type=row.get('var_type')) 61 | if not value: 62 | raise EnvsValueException('{}: Environment Variable Not Set'.format(row.get('key'))) 63 | os.remove(ENVS_RESULT_FILENAME) 64 | -------------------------------------------------------------------------------- /envs/exceptions.py: -------------------------------------------------------------------------------- 1 | class EnvsValueException(Exception): 2 | pass 3 | -------------------------------------------------------------------------------- /envs/templates/settings.jinja2: -------------------------------------------------------------------------------- 1 | from envs import env 2 | 3 | {% for obj in attr_list %} 4 | {{ obj.name }} = {% if not obj.convert %}{% if obj.var_type == 'string' %}"{% endif %}{{ obj.default_val }}{% if obj.var_type == 'string' %}"{% endif %}{% else %}env('{{ obj.name }}',{% if obj.var_type == 'string' %}"{% endif %}{{ obj.default_val }}{% if obj.var_type == 'string' %}"{% endif %},var_type='{{ obj.var_type }}'){% endif %} 5 | {% endfor %} -------------------------------------------------------------------------------- /envs/test_settings.py: -------------------------------------------------------------------------------- 1 | from envs import env 2 | 3 | DATABASE_URL = env('DATABASE_URL') 4 | 5 | DEBUG = env('DEBUG', False, var_type='boolean') 6 | 7 | MIDDLEWARE = env('MIDDLEWARE', [], var_type='list') 8 | -------------------------------------------------------------------------------- /envs/tests.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | from decimal import Decimal, InvalidOperation 4 | import json 5 | 6 | try: 7 | # python 3.4+ should use builtin unittest.mock not mock package 8 | from unittest.mock import patch 9 | from unittest import mock 10 | except ImportError: 11 | from mock import patch 12 | import mock 13 | 14 | import sys 15 | 16 | from envs import env 17 | from envs.exceptions import EnvsValueException 18 | 19 | class EnvTestCase(unittest.TestCase): 20 | def setUp(self): 21 | # Integer 22 | os.environ.setdefault('VALID_INTEGER', '1') 23 | os.environ.setdefault('INVALID_INTEGER', '["seven"]') 24 | # String 25 | os.environ.setdefault('VALID_STRING', 'seven') 26 | # Boolean 27 | os.environ.setdefault('VALID_BOOLEAN', 'True') 28 | os.environ.setdefault('VALID_BOOLEAN_FALSE', 'false') 29 | os.environ.setdefault('INVALID_BOOLEAN', 'seven') 30 | # List 31 | os.environ.setdefault('VALID_LIST', "['1','2','3']") 32 | os.environ.setdefault('INVALID_LIST', "1") 33 | # Tuple 34 | os.environ.setdefault('VALID_TUPLE', "('True','FALSE')") 35 | os.environ.setdefault('INVALID_TUPLE', '1') 36 | # Dict 37 | os.environ.setdefault('VALID_DICT', "{'first_name':'Suge'}") 38 | os.environ.setdefault('INVALID_DICT', 'Aaron Rogers') 39 | # Float 40 | os.environ.setdefault('VALID_FLOAT', "5.0") 41 | os.environ.setdefault('INVALID_FLOAT', '[5.0]') 42 | # Decimal 43 | os.environ.setdefault('VALID_DECIMAL', "2.39") 44 | os.environ.setdefault('INVALID_DECIMAL', "FOOBAR") 45 | 46 | def test_integer_valid(self): 47 | self.assertEqual(1, env('VALID_INTEGER', var_type='integer')) 48 | 49 | def test_integer_invalid(self): 50 | with self.assertRaises(TypeError) as vm: 51 | env('INVALID_INTEGER', var_type='integer') 52 | 53 | def test_wrong_var_type(self): 54 | with self.assertRaises(ValueError) as vm: 55 | env('INVALID_INTEGER', var_type='set') 56 | 57 | def test_string_valid(self): 58 | self.assertEqual('seven', env('VALID_STRING')) 59 | 60 | def test_boolean_valid(self): 61 | self.assertEqual(True, env('VALID_BOOLEAN', var_type='boolean')) 62 | 63 | def test_boolean_valid_false(self): 64 | self.assertEqual(False, env('VALID_BOOLEAN_FALSE', var_type='boolean')) 65 | 66 | def test_boolean_invalid(self): 67 | with self.assertRaises(ValueError) as vm: 68 | env('INVALID_BOOLEAN', var_type='boolean') 69 | 70 | def test_list_valid(self): 71 | self.assertEqual(['1', '2', '3'], env('VALID_LIST', var_type='list')) 72 | 73 | def test_list_invalid(self): 74 | with self.assertRaises(TypeError) as vm: 75 | env('INVALID_LIST', var_type='list') 76 | 77 | def test_tuple_valid(self): 78 | self.assertEqual(('True', 'FALSE'), env('VALID_TUPLE', var_type='tuple')) 79 | 80 | def test_tuple_invalid(self): 81 | with self.assertRaises(TypeError) as vm: 82 | env('INVALID_TUPLE', var_type='tuple') 83 | 84 | def test_dict_valid(self): 85 | self.assertEqual({'first_name': 'Suge'}, env('VALID_DICT', var_type='dict')) 86 | 87 | def test_dict_invalid(self): 88 | with self.assertRaises(SyntaxError) as vm: 89 | env('INVALID_DICT', var_type='dict') 90 | 91 | def test_float_valid(self): 92 | self.assertEqual(5.0, env('VALID_FLOAT', var_type='float')) 93 | 94 | def test_float_invalid(self): 95 | with self.assertRaises(TypeError) as vm: 96 | env('INVALID_FLOAT', var_type='float') 97 | 98 | def test_decimal_valid(self): 99 | self.assertEqual(Decimal('2.39'), env('VALID_DECIMAL', var_type='decimal')) 100 | 101 | def test_decimal_invalid(self): 102 | with self.assertRaises(ArithmeticError) as vm: 103 | env('INVALID_DECIMAL', var_type='decimal') 104 | 105 | def test_defaults(self): 106 | self.assertEqual(env('HELLO', 5, var_type='integer'), 5) 107 | self.assertEqual(env('HELLO', 5.0, var_type='float'), 5.0) 108 | self.assertEqual(env('HELLO', [], var_type='list'), []) 109 | self.assertEqual(env('HELLO', {}, var_type='dict'), {}) 110 | self.assertEqual(env('HELLO', (), var_type='tuple'), ()) 111 | self.assertEqual(env('HELLO', 'world'), 'world') 112 | self.assertEqual(env('HELLO', False, var_type='boolean'), False) 113 | self.assertEqual(env('HELLO', 'False', var_type='boolean'), False) 114 | self.assertEqual(env('HELLO', 'true', var_type='boolean'), True) 115 | self.assertEqual(env('HELLO', Decimal('3.14'), var_type='decimal'), Decimal('3.14')) 116 | 117 | def test_without_defaults_allow_none(self): 118 | self.assertEqual(env('HELLO'), None) 119 | self.assertEqual(env('HELLO', var_type='integer'), None) 120 | self.assertEqual(env('HELLO', var_type='float'), None) 121 | self.assertEqual(env('HELLO', var_type='list'), None) 122 | 123 | def test_without_defaults_disallow_none(self): 124 | with self.assertRaises(EnvsValueException): 125 | env('HELLO', allow_none=False) 126 | with self.assertRaises(EnvsValueException): 127 | env('HELLO', var_type='integer', allow_none=False) 128 | with self.assertRaises(EnvsValueException): 129 | env('HELLO', var_type='float', allow_none=False) 130 | with self.assertRaises(EnvsValueException): 131 | env('HELLO', var_type='list', allow_none=False) 132 | 133 | def test_empty_values(self): 134 | os.environ.setdefault('EMPTY', '') 135 | self.assertEqual(env('EMPTY'), '') 136 | with self.assertRaises(SyntaxError): 137 | env('EMPTY', var_type='integer') 138 | with self.assertRaises(SyntaxError): 139 | env('EMPTY', var_type='float') 140 | with self.assertRaises(SyntaxError): 141 | env('EMPTY', var_type='list') 142 | with self.assertRaises(SyntaxError): 143 | env('EMPTY', var_type='dict') 144 | with self.assertRaises(SyntaxError): 145 | env('EMPTY', var_type='tuple') 146 | with self.assertRaises(ValueError): 147 | env('EMPTY', var_type='boolean') 148 | with self.assertRaises(ArithmeticError): 149 | env('EMPTY', var_type='decimal') 150 | 151 | ''' 152 | Each CLI Test must be run outside of test suites in isolation 153 | since Click CLI Runner alters the global context 154 | ''' 155 | def setup_CliRunner(test_func): 156 | ''' 157 | Decorator to initialize environment for CliRunner. 158 | ''' 159 | def wrapper(): 160 | from click.testing import CliRunner 161 | try: 162 | from cli import envs as cli_envs 163 | except ImportError: 164 | from .cli import envs as cli_envs 165 | 166 | try: 167 | from cli import envs 168 | except ImportError: 169 | from .cli import envs 170 | 171 | test_func() 172 | 173 | return wrapper 174 | 175 | @mock.patch.object(sys, 'argv', ["list-envs"]) 176 | @setup_CliRunner 177 | def test_list_envs(): 178 | os.environ.setdefault('DEBUG', 'True') 179 | 180 | runner = CliRunner() 181 | result = runner.invoke(envs, ['list-envs', '--settings-file', 'envs.test_settings', '--keep-result', 'True'], catch_exceptions=False) 182 | 183 | output_expected = [{"default": None, "value": None, "var_type": "string", "key": "DATABASE_URL"},{"default": False, "value": "True", "var_type": "boolean", "key": "DEBUG"},{"default": [], "value": None, "var_type": "list", "key": "MIDDLEWARE"},{}] 184 | 185 | with open('.envs_result', 'r') as f: 186 | output_actual = json.load(f) 187 | 188 | exit_code_expected = 0 189 | exit_code_actual = result.exit_code 190 | 191 | 192 | assert exit_code_actual == exit_code_expected 193 | assert output_actual == output_expected 194 | 195 | 196 | 197 | 198 | 199 | if __name__ == '__main__': 200 | unittest.main() 201 | 202 | -------------------------------------------------------------------------------- /envs/util.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import importlib 3 | import json 4 | import os 5 | import sys 6 | 7 | from . import Env, ENVS_RESULT_FILENAME 8 | 9 | VAR_TYPES = Env.valid_types.keys() 10 | 11 | if sys.version_info >= (3, 0): 12 | raw_input = input 13 | 14 | def import_util(imp): 15 | """ 16 | Lazily imports a utils (class, 17 | function,or variable) from a module) from 18 | a string. 19 | @param imp: 20 | """ 21 | 22 | mod_name, obj_name = imp.rsplit('.', 1) 23 | mod = importlib.import_module(mod_name) 24 | return getattr(mod, obj_name) 25 | 26 | 27 | def convert_module(module): 28 | attr_list = [] 29 | for k, v in module.__dict__.items(): 30 | if k.isupper(): 31 | convert = bool(int(raw_input('Convert {}? (1=True,0=False): '.format(k)))) 32 | attr_dict = {'name': k, 'convert': convert} 33 | default_val = None 34 | if convert: 35 | 36 | default_val = raw_input('Default Value? (default: {}): '.format(v)) 37 | if default_val: 38 | default_val = ast.literal_eval(default_val) 39 | if not default_val: 40 | default_val = v 41 | attr_dict['default_val'] = default_val 42 | 43 | var_type = raw_input('Variable Type Choices (ex. boolean,string,list,tuple,integer,float,dict): ') 44 | if not var_type in VAR_TYPES: 45 | raise ValueError('{} not in {}'.format(var_type, VAR_TYPES)) 46 | attr_dict['var_type'] = var_type 47 | if not default_val: 48 | default_val = v 49 | attr_list.append(attr_dict) 50 | return attr_list 51 | 52 | 53 | def import_mod(module): 54 | if sys.version_info.major == 3: 55 | try: 56 | m = importlib.import_module(module) 57 | except ModuleNotFoundError: 58 | sys.path.insert(0, os.getcwd()) 59 | m = importlib.import_module(module) 60 | else: 61 | try: 62 | m = importlib.import_module(module) 63 | except ImportError: 64 | sys.path.insert(0, os.getcwd()) 65 | m = importlib.import_module(module) 66 | return m 67 | 68 | 69 | def list_envs_module(module): 70 | with open(ENVS_RESULT_FILENAME, 'w+') as f: 71 | f.write('[') 72 | import_mod(module) 73 | with open(ENVS_RESULT_FILENAME, 'a') as f: 74 | f.write('{}]') 75 | with open(ENVS_RESULT_FILENAME, 'r') as f: 76 | envs_result = json.load(f) 77 | envs_result.pop() 78 | return envs_result 79 | -------------------------------------------------------------------------------- /requirements_cli.txt: -------------------------------------------------------------------------------- 1 | jinja2>=2.8 2 | click>=6.6 3 | terminaltables>=3.0.0 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | 4 | def parse_requirements(filename): 5 | """ load requirements from a pip requirements file """ 6 | lineiter = (line.strip() for line in open(filename)) 7 | return [line for line in lineiter if line and not line.startswith("#")] 8 | 9 | 10 | setup( 11 | name='envs', 12 | description='Easy access of environment variables from Python with support for strings, booleans, list, tuples, and dicts.', 13 | url='https://github.com/bjinwright/envs', 14 | author='Brian Jinwright', 15 | license='Apache License 2.0', 16 | keywords='environment variables', 17 | extras_require={ 18 | 'cli': parse_requirements('requirements_cli.txt'), 19 | }, 20 | packages=find_packages(), 21 | py_modules=['envs.cli'], 22 | include_package_data=True, 23 | zip_safe=True, 24 | version='1.3', 25 | entry_points=''' 26 | [console_scripts] 27 | envs=envs.cli:envs 28 | ''', 29 | ) 30 | 31 | -------------------------------------------------------------------------------- /test-requirements.txt: -------------------------------------------------------------------------------- 1 | coverage==4.2 2 | nose==1.3.7 3 | mock 4 | jinja2>=2.8 5 | click>=6.6 6 | terminaltables>=3.0.0 7 | --------------------------------------------------------------------------------