python-decouple


Namepython-decouple JSON
Version 3.6 PyPI version JSON
download
home_pagehttp://github.com/henriquebastos/python-decouple/
SummaryStrict separation of settings from code.
upload_time2022-02-02 19:25:31
maintainer
docs_urlNone
authorHenrique Bastos
requires_python
licenseMIT
keywords
VCS
bugtrack_url
requirements mock pytest tox docutils Pygments twine
Travis-CI
coveralls test coverage No coveralls.
            Python Decouple: Strict separation of settings from code
========================================================

*Decouple* helps you to organize your settings so that you can
change parameters without having to redeploy your app.

It also makes it easy for you to:

#. store parameters in *ini* or *.env* files;
#. define comprehensive default values;
#. properly convert values to the correct data type;
#. have **only one** configuration module to rule all your instances.

It was originally designed for Django, but became an independent generic tool
for separating settings from code.

.. image:: https://img.shields.io/travis/henriquebastos/python-decouple.svg
    :target: https://travis-ci.org/henriquebastos/python-decouple
    :alt: Build Status

.. image:: https://img.shields.io/pypi/v/python-decouple.svg
    :target: https://pypi.python.org/pypi/python-decouple/
    :alt: Latest PyPI version



.. contents:: Summary


Why?
====

The settings files in web frameworks store many different kinds of parameters:

* Locale and i18n;
* Middlewares and Installed Apps;
* Resource handles to the database, Memcached, and other backing services;
* Credentials to external services such as Amazon S3 or Twitter;
* Per-deploy values such as the canonical hostname for the instance.

The first 2 are *project settings* and the last 3 are *instance settings*.

You should be able to change *instance settings* without redeploying your app.

Why not just use environment variables?
---------------------------------------

*Envvars* works, but since ``os.environ`` only returns strings, it's tricky.

Let's say you have an *envvar* ``DEBUG=False``. If you run:

.. code-block:: python

    if os.environ['DEBUG']:
        print True
    else:
        print False

It will print **True**, because ``os.environ['DEBUG']`` returns the **string** ``"False"``.
Since it's a non-empty string, it will be evaluated as True.

*Decouple* provides a solution that doesn't look like a workaround: ``config('DEBUG', cast=bool)``.

Usage
=====

Install:

.. code-block:: console

    pip install python-decouple


Then use it on your ``settings.py``.

#. Import the ``config`` object:

   .. code-block:: python

     from decouple import config

#. Retrieve the configuration parameters:

   .. code-block:: python

     SECRET_KEY = config('SECRET_KEY')
     DEBUG = config('DEBUG', default=False, cast=bool)
     EMAIL_HOST = config('EMAIL_HOST', default='localhost')
     EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)

Encodings
---------
Decouple's default encoding is `UTF-8`.

But you can specify your preferred encoding.

Since `config` is lazy and only opens the configuration file when it's first needed, you have the chance to change
its encoding right after import.

.. code-block:: python

    from decouple import config
    config.encoding = 'cp1251'
    SECRET_KEY = config('SECRET_KEY')

If you wish to fall back to your system's default encoding use:

.. code-block:: python

    import locale
    from decouple import config
    config.encoding = locale.getpreferredencoding(False)
    SECRET_KEY = config('SECRET_KEY')

Where is the settings data stored?
-----------------------------------

*Decouple* supports both *.ini* and *.env* files.

Ini file
~~~~~~~~

Simply create a ``settings.ini`` next to your configuration module in the form:

.. code-block:: ini

    [settings]
    DEBUG=True
    TEMPLATE_DEBUG=%(DEBUG)s
    SECRET_KEY=ARANDOMSECRETKEY
    DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase
    PERCENTILE=90%%
    #COMMENTED=42

*Note*: Since ``ConfigParser`` supports *string interpolation*, to represent the character ``%`` you need to escape it as ``%%``.

Env file
~~~~~~~~

Simply create a ``.env`` text file in your repository's root directory in the form:

.. code-block:: console

    DEBUG=True
    TEMPLATE_DEBUG=True
    SECRET_KEY=ARANDOMSECRETKEY
    DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase
    PERCENTILE=90%
    #COMMENTED=42

Example: How do I use it with Django?
-------------------------------------

Given that I have a ``.env`` file in my repository's root directory, here is a snippet of my ``settings.py``.

I also recommend using `pathlib <https://docs.python.org/3/library/pathlib.html>`_
and `dj-database-url <https://pypi.python.org/pypi/dj-database-url/>`_.

.. code-block:: python

    # coding: utf-8
    from decouple import config
    from unipath import Path
    from dj_database_url import parse as db_url


    BASE_DIR = Path(__file__).parent

    DEBUG = config('DEBUG', default=False, cast=bool)
    TEMPLATE_DEBUG = DEBUG

    DATABASES = {
        'default': config(
            'DATABASE_URL',
            default='sqlite:///' + BASE_DIR.child('db.sqlite3'),
            cast=db_url
        )
    }

    TIME_ZONE = 'America/Sao_Paulo'
    USE_L10N = True
    USE_TZ = True

    SECRET_KEY = config('SECRET_KEY')

    EMAIL_HOST = config('EMAIL_HOST', default='localhost')
    EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)
    EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='')
    EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='')
    EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=False, cast=bool)

    # ...

Attention with *undefined* parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In the above example, all configuration parameters except ``SECRET_KEY = config('SECRET_KEY')``
have a default value in case it does not exist in the ``.env`` file.

If ``SECRET_KEY`` is not present in the ``.env``, *decouple* will raise an ``UndefinedValueError``.

This *fail fast* policy helps you avoid chasing misbehaviours when you eventually forget a parameter.

Overriding config files with environment variables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sometimes you may want to change a parameter value without having to edit the ``.ini`` or ``.env`` files.

Since version 3.0, *decouple* respects the *unix way*.
Therefore environment variables have precedence over config files.

To override a config parameter you can simply do:

.. code-block:: console

    DEBUG=True python manage.py


How does it work?
=================

*Decouple* always searches for *Options* in this order:

#. Environment variables;
#. Repository: ini or .env file;
#. Default argument passed to config.

There are 4 classes doing the magic:


- ``Config``

    Coordinates all the configuration retrieval.

- ``RepositoryIni``

    Can read values from ``os.environ`` and ini files, in that order.

    **Note:** Since version 3.0 *decouple* respects unix precedence of environment variables *over* config files.

- ``RepositoryEnv``

    Can read values from ``os.environ`` and ``.env`` files.

    **Note:** Since version 3.0 *decouple* respects unix precedence of environment variables *over* config files.

- ``AutoConfig``

    This is a *lazy* ``Config`` factory that detects which configuration repository you're using.

    It recursively searches up your configuration module path looking for a
    ``settings.ini`` or a ``.env`` file.

    Optionally, it accepts ``search_path`` argument to explicitly define
    where the search starts.

The **config** object is an instance of ``AutoConfig`` that instantiates a ``Config`` with the proper ``Repository``
on the first time it is used.


Understanding the CAST argument
-------------------------------

By default, all values returned by ``decouple`` are ``strings``, after all they are
read from ``text files`` or the ``envvars``.

However, your Python code may expect some other value type, for example:

* Django's ``DEBUG`` expects a boolean ``True`` or ``False``.
* Django's ``EMAIL_PORT`` expects an ``integer``.
* Django's ``ALLOWED_HOSTS`` expects a ``list`` of hostnames.
* Django's ``SECURE_PROXY_SSL_HEADER`` expects a ``tuple`` with two elements, the name of the header to look for and the required value.

To meet this need, the ``config`` function accepts a ``cast`` argument which
receives any *callable*, that will be used to *transform* the string value
into something else.

Let's see some examples for the above mentioned cases:

.. code-block:: python

    >>> os.environ['DEBUG'] = 'False'
    >>> config('DEBUG', cast=bool)
    False

    >>> os.environ['EMAIL_PORT'] = '42'
    >>> config('EMAIL_PORT', cast=int)
    42

    >>> os.environ['ALLOWED_HOSTS'] = '.localhost, .herokuapp.com'
    >>> config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')])
    ['.localhost', '.herokuapp.com']

    >>> os.environ['SECURE_PROXY_SSL_HEADER'] = 'HTTP_X_FORWARDED_PROTO, https'
    >>> config('SECURE_PROXY_SSL_HEADER', cast=Csv(post_process=tuple))
    ('HTTP_X_FORWARDED_PROTO', 'https')

As you can see, ``cast`` is very flexible. But the last example got a bit complex.

Built in Csv Helper
~~~~~~~~~~~~~~~~~~~

To address the complexity of the last example, *Decouple* comes with an extensible *Csv helper*.

Let's improve the last example:

.. code-block:: python

    >>> from decouple import Csv
    >>> os.environ['ALLOWED_HOSTS'] = '.localhost, .herokuapp.com'
    >>> config('ALLOWED_HOSTS', cast=Csv())
    ['.localhost', '.herokuapp.com']

You can also have a `default` value that must be a string to be processed by `Csv`.

.. code-block:: python

    >>> from decouple import Csv
    >>> config('ALLOWED_HOSTS', default='127.0.0.1', cast=Csv())
    ['127.0.0.1']

You can also parametrize the *Csv Helper* to return other types of data.

.. code-block:: python

    >>> os.environ['LIST_OF_INTEGERS'] = '1,2,3,4,5'
    >>> config('LIST_OF_INTEGERS', cast=Csv(int))
    [1, 2, 3, 4, 5]

    >>> os.environ['COMPLEX_STRING'] = '%virtual_env%\t *important stuff*\t   trailing spaces   '
    >>> csv = Csv(cast=lambda s: s.upper(), delimiter='\t', strip=' %*')
    >>> csv(os.environ['COMPLEX_STRING'])
    ['VIRTUAL_ENV', 'IMPORTANT STUFF', 'TRAILING SPACES']

By default *Csv* returns a ``list``, but you can get a ``tuple`` or whatever you want using the ``post_process`` argument:

.. code-block:: python

    >>> os.environ['SECURE_PROXY_SSL_HEADER'] = 'HTTP_X_FORWARDED_PROTO, https'
    >>> config('SECURE_PROXY_SSL_HEADER', cast=Csv(post_process=tuple))
    ('HTTP_X_FORWARDED_PROTO', 'https')

Built in Choices helper
~~~~~~~~~~~~~~~~~~~~~~~

Allows for cast and validation based on a list of choices. For example:

.. code-block:: python

    >>> from decouple import config, Choices
    >>> os.environ['CONNECTION_TYPE'] = 'usb'
    >>> config('CONNECTION_TYPE', cast=Choices(['eth', 'usb', 'bluetooth']))
    'usb'

    >>> os.environ['CONNECTION_TYPE'] = 'serial'
    >>> config('CONNECTION_TYPE', cast=Choices(['eth', 'usb', 'bluetooth']))
    Traceback (most recent call last):
     ...
    ValueError: Value not in list: 'serial'; valid values are ['eth', 'usb', 'bluetooth']

You can also parametrize *Choices helper* to cast to another type:

.. code-block:: python

    >>> os.environ['SOME_NUMBER'] = '42'
    >>> config('SOME_NUMBER', cast=Choices([7, 14, 42], cast=int))
    42

You can also use a Django-like choices tuple:

.. code-block:: python

    >>> USB = 'usb'
    >>> ETH = 'eth'
    >>> BLUETOOTH = 'bluetooth'
    >>>
    >>> CONNECTION_OPTIONS = (
    ...        (USB, 'USB'),
    ...        (ETH, 'Ethernet'),
    ...        (BLUETOOTH, 'Bluetooth'),)
    ...
    >>> os.environ['CONNECTION_TYPE'] = BLUETOOTH
    >>> config('CONNECTION_TYPE', cast=Choices(choices=CONNECTION_OPTIONS))
    'bluetooth'

Contribute
==========

Your contribution is welcome.

Setup your development environment:

.. code-block:: console

    git clone git@github.com:henriquebastos/python-decouple.git
    cd python-decouple
    python -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt
    tox

*Decouple* supports both Python 2.7 and 3.6. Make sure you have both installed.

I use `pyenv <https://github.com/pyenv/pyenv#simple-python-version-management-pyenv>`_ to
manage multiple Python versions and I described my workspace setup on this article:
`The definitive guide to setup my Python workspace
<https://medium.com/@henriquebastos/the-definitive-guide-to-setup-my-python-workspace-628d68552e14>`_

You can submit pull requests and issues for discussion. However I only
consider merging tested code.


License
=======

The MIT License (MIT)

Copyright (c) 2017 Henrique Bastos <henrique at bastos dot net>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.



            

Raw data

            {
    "_id": null,
    "home_page": "http://github.com/henriquebastos/python-decouple/",
    "name": "python-decouple",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Henrique Bastos",
    "author_email": "henrique@bastos.net",
    "download_url": "https://files.pythonhosted.org/packages/ad/90/b49583e8dfb94c3b699070701ae6a8415de6c0445c1df9c11f912e051316/python-decouple-3.6.tar.gz",
    "platform": "any",
    "description": "Python Decouple: Strict separation of settings from code\n========================================================\n\n*Decouple* helps you to organize your settings so that you can\nchange parameters without having to redeploy your app.\n\nIt also makes it easy for you to:\n\n#. store parameters in *ini* or *.env* files;\n#. define comprehensive default values;\n#. properly convert values to the correct data type;\n#. have **only one** configuration module to rule all your instances.\n\nIt was originally designed for Django, but became an independent generic tool\nfor separating settings from code.\n\n.. image:: https://img.shields.io/travis/henriquebastos/python-decouple.svg\n    :target: https://travis-ci.org/henriquebastos/python-decouple\n    :alt: Build Status\n\n.. image:: https://img.shields.io/pypi/v/python-decouple.svg\n    :target: https://pypi.python.org/pypi/python-decouple/\n    :alt: Latest PyPI version\n\n\n\n.. contents:: Summary\n\n\nWhy?\n====\n\nThe settings files in web frameworks store many different kinds of parameters:\n\n* Locale and i18n;\n* Middlewares and Installed Apps;\n* Resource handles to the database, Memcached, and other backing services;\n* Credentials to external services such as Amazon S3 or Twitter;\n* Per-deploy values such as the canonical hostname for the instance.\n\nThe first 2 are *project settings* and the last 3 are *instance settings*.\n\nYou should be able to change *instance settings* without redeploying your app.\n\nWhy not just use environment variables?\n---------------------------------------\n\n*Envvars* works, but since ``os.environ`` only returns strings, it's tricky.\n\nLet's say you have an *envvar* ``DEBUG=False``. If you run:\n\n.. code-block:: python\n\n    if os.environ['DEBUG']:\n        print True\n    else:\n        print False\n\nIt will print **True**, because ``os.environ['DEBUG']`` returns the **string** ``\"False\"``.\nSince it's a non-empty string, it will be evaluated as True.\n\n*Decouple* provides a solution that doesn't look like a workaround: ``config('DEBUG', cast=bool)``.\n\nUsage\n=====\n\nInstall:\n\n.. code-block:: console\n\n    pip install python-decouple\n\n\nThen use it on your ``settings.py``.\n\n#. Import the ``config`` object:\n\n   .. code-block:: python\n\n     from decouple import config\n\n#. Retrieve the configuration parameters:\n\n   .. code-block:: python\n\n     SECRET_KEY = config('SECRET_KEY')\n     DEBUG = config('DEBUG', default=False, cast=bool)\n     EMAIL_HOST = config('EMAIL_HOST', default='localhost')\n     EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)\n\nEncodings\n---------\nDecouple's default encoding is `UTF-8`.\n\nBut you can specify your preferred encoding.\n\nSince `config` is lazy and only opens the configuration file when it's first needed, you have the chance to change\nits encoding right after import.\n\n.. code-block:: python\n\n    from decouple import config\n    config.encoding = 'cp1251'\n    SECRET_KEY = config('SECRET_KEY')\n\nIf you wish to fall back to your system's default encoding use:\n\n.. code-block:: python\n\n    import locale\n    from decouple import config\n    config.encoding = locale.getpreferredencoding(False)\n    SECRET_KEY = config('SECRET_KEY')\n\nWhere is the settings data stored?\n-----------------------------------\n\n*Decouple* supports both *.ini* and *.env* files.\n\nIni file\n~~~~~~~~\n\nSimply create a ``settings.ini`` next to your configuration module in the form:\n\n.. code-block:: ini\n\n    [settings]\n    DEBUG=True\n    TEMPLATE_DEBUG=%(DEBUG)s\n    SECRET_KEY=ARANDOMSECRETKEY\n    DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase\n    PERCENTILE=90%%\n    #COMMENTED=42\n\n*Note*: Since ``ConfigParser`` supports *string interpolation*, to represent the character ``%`` you need to escape it as ``%%``.\n\nEnv file\n~~~~~~~~\n\nSimply create a ``.env`` text file in your repository's root directory in the form:\n\n.. code-block:: console\n\n    DEBUG=True\n    TEMPLATE_DEBUG=True\n    SECRET_KEY=ARANDOMSECRETKEY\n    DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase\n    PERCENTILE=90%\n    #COMMENTED=42\n\nExample: How do I use it with Django?\n-------------------------------------\n\nGiven that I have a ``.env`` file in my repository's root directory, here is a snippet of my ``settings.py``.\n\nI also recommend using `pathlib <https://docs.python.org/3/library/pathlib.html>`_\nand `dj-database-url <https://pypi.python.org/pypi/dj-database-url/>`_.\n\n.. code-block:: python\n\n    # coding: utf-8\n    from decouple import config\n    from unipath import Path\n    from dj_database_url import parse as db_url\n\n\n    BASE_DIR = Path(__file__).parent\n\n    DEBUG = config('DEBUG', default=False, cast=bool)\n    TEMPLATE_DEBUG = DEBUG\n\n    DATABASES = {\n        'default': config(\n            'DATABASE_URL',\n            default='sqlite:///' + BASE_DIR.child('db.sqlite3'),\n            cast=db_url\n        )\n    }\n\n    TIME_ZONE = 'America/Sao_Paulo'\n    USE_L10N = True\n    USE_TZ = True\n\n    SECRET_KEY = config('SECRET_KEY')\n\n    EMAIL_HOST = config('EMAIL_HOST', default='localhost')\n    EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)\n    EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='')\n    EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='')\n    EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=False, cast=bool)\n\n    # ...\n\nAttention with *undefined* parameters\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn the above example, all configuration parameters except ``SECRET_KEY = config('SECRET_KEY')``\nhave a default value in case it does not exist in the ``.env`` file.\n\nIf ``SECRET_KEY`` is not present in the ``.env``, *decouple* will raise an ``UndefinedValueError``.\n\nThis *fail fast* policy helps you avoid chasing misbehaviours when you eventually forget a parameter.\n\nOverriding config files with environment variables\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSometimes you may want to change a parameter value without having to edit the ``.ini`` or ``.env`` files.\n\nSince version 3.0, *decouple* respects the *unix way*.\nTherefore environment variables have precedence over config files.\n\nTo override a config parameter you can simply do:\n\n.. code-block:: console\n\n    DEBUG=True python manage.py\n\n\nHow does it work?\n=================\n\n*Decouple* always searches for *Options* in this order:\n\n#. Environment variables;\n#. Repository: ini or .env file;\n#. Default argument passed to config.\n\nThere are 4 classes doing the magic:\n\n\n- ``Config``\n\n    Coordinates all the configuration retrieval.\n\n- ``RepositoryIni``\n\n    Can read values from ``os.environ`` and ini files, in that order.\n\n    **Note:** Since version 3.0 *decouple* respects unix precedence of environment variables *over* config files.\n\n- ``RepositoryEnv``\n\n    Can read values from ``os.environ`` and ``.env`` files.\n\n    **Note:** Since version 3.0 *decouple* respects unix precedence of environment variables *over* config files.\n\n- ``AutoConfig``\n\n    This is a *lazy* ``Config`` factory that detects which configuration repository you're using.\n\n    It recursively searches up your configuration module path looking for a\n    ``settings.ini`` or a ``.env`` file.\n\n    Optionally, it accepts ``search_path`` argument to explicitly define\n    where the search starts.\n\nThe **config** object is an instance of ``AutoConfig`` that instantiates a ``Config`` with the proper ``Repository``\non the first time it is used.\n\n\nUnderstanding the CAST argument\n-------------------------------\n\nBy default, all values returned by ``decouple`` are ``strings``, after all they are\nread from ``text files`` or the ``envvars``.\n\nHowever, your Python code may expect some other value type, for example:\n\n* Django's ``DEBUG`` expects a boolean ``True`` or ``False``.\n* Django's ``EMAIL_PORT`` expects an ``integer``.\n* Django's ``ALLOWED_HOSTS`` expects a ``list`` of hostnames.\n* Django's ``SECURE_PROXY_SSL_HEADER`` expects a ``tuple`` with two elements, the name of the header to look for and the required value.\n\nTo meet this need, the ``config`` function accepts a ``cast`` argument which\nreceives any *callable*, that will be used to *transform* the string value\ninto something else.\n\nLet's see some examples for the above mentioned cases:\n\n.. code-block:: python\n\n    >>> os.environ['DEBUG'] = 'False'\n    >>> config('DEBUG', cast=bool)\n    False\n\n    >>> os.environ['EMAIL_PORT'] = '42'\n    >>> config('EMAIL_PORT', cast=int)\n    42\n\n    >>> os.environ['ALLOWED_HOSTS'] = '.localhost, .herokuapp.com'\n    >>> config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')])\n    ['.localhost', '.herokuapp.com']\n\n    >>> os.environ['SECURE_PROXY_SSL_HEADER'] = 'HTTP_X_FORWARDED_PROTO, https'\n    >>> config('SECURE_PROXY_SSL_HEADER', cast=Csv(post_process=tuple))\n    ('HTTP_X_FORWARDED_PROTO', 'https')\n\nAs you can see, ``cast`` is very flexible. But the last example got a bit complex.\n\nBuilt in Csv Helper\n~~~~~~~~~~~~~~~~~~~\n\nTo address the complexity of the last example, *Decouple* comes with an extensible *Csv helper*.\n\nLet's improve the last example:\n\n.. code-block:: python\n\n    >>> from decouple import Csv\n    >>> os.environ['ALLOWED_HOSTS'] = '.localhost, .herokuapp.com'\n    >>> config('ALLOWED_HOSTS', cast=Csv())\n    ['.localhost', '.herokuapp.com']\n\nYou can also have a `default` value that must be a string to be processed by `Csv`.\n\n.. code-block:: python\n\n    >>> from decouple import Csv\n    >>> config('ALLOWED_HOSTS', default='127.0.0.1', cast=Csv())\n    ['127.0.0.1']\n\nYou can also parametrize the *Csv Helper* to return other types of data.\n\n.. code-block:: python\n\n    >>> os.environ['LIST_OF_INTEGERS'] = '1,2,3,4,5'\n    >>> config('LIST_OF_INTEGERS', cast=Csv(int))\n    [1, 2, 3, 4, 5]\n\n    >>> os.environ['COMPLEX_STRING'] = '%virtual_env%\\t *important stuff*\\t   trailing spaces   '\n    >>> csv = Csv(cast=lambda s: s.upper(), delimiter='\\t', strip=' %*')\n    >>> csv(os.environ['COMPLEX_STRING'])\n    ['VIRTUAL_ENV', 'IMPORTANT STUFF', 'TRAILING SPACES']\n\nBy default *Csv* returns a ``list``, but you can get a ``tuple`` or whatever you want using the ``post_process`` argument:\n\n.. code-block:: python\n\n    >>> os.environ['SECURE_PROXY_SSL_HEADER'] = 'HTTP_X_FORWARDED_PROTO, https'\n    >>> config('SECURE_PROXY_SSL_HEADER', cast=Csv(post_process=tuple))\n    ('HTTP_X_FORWARDED_PROTO', 'https')\n\nBuilt in Choices helper\n~~~~~~~~~~~~~~~~~~~~~~~\n\nAllows for cast and validation based on a list of choices. For example:\n\n.. code-block:: python\n\n    >>> from decouple import config, Choices\n    >>> os.environ['CONNECTION_TYPE'] = 'usb'\n    >>> config('CONNECTION_TYPE', cast=Choices(['eth', 'usb', 'bluetooth']))\n    'usb'\n\n    >>> os.environ['CONNECTION_TYPE'] = 'serial'\n    >>> config('CONNECTION_TYPE', cast=Choices(['eth', 'usb', 'bluetooth']))\n    Traceback (most recent call last):\n     ...\n    ValueError: Value not in list: 'serial'; valid values are ['eth', 'usb', 'bluetooth']\n\nYou can also parametrize *Choices helper* to cast to another type:\n\n.. code-block:: python\n\n    >>> os.environ['SOME_NUMBER'] = '42'\n    >>> config('SOME_NUMBER', cast=Choices([7, 14, 42], cast=int))\n    42\n\nYou can also use a Django-like choices tuple:\n\n.. code-block:: python\n\n    >>> USB = 'usb'\n    >>> ETH = 'eth'\n    >>> BLUETOOTH = 'bluetooth'\n    >>>\n    >>> CONNECTION_OPTIONS = (\n    ...        (USB, 'USB'),\n    ...        (ETH, 'Ethernet'),\n    ...        (BLUETOOTH, 'Bluetooth'),)\n    ...\n    >>> os.environ['CONNECTION_TYPE'] = BLUETOOTH\n    >>> config('CONNECTION_TYPE', cast=Choices(choices=CONNECTION_OPTIONS))\n    'bluetooth'\n\nContribute\n==========\n\nYour contribution is welcome.\n\nSetup your development environment:\n\n.. code-block:: console\n\n    git clone git@github.com:henriquebastos/python-decouple.git\n    cd python-decouple\n    python -m venv .venv\n    source .venv/bin/activate\n    pip install -r requirements.txt\n    tox\n\n*Decouple* supports both Python 2.7 and 3.6. Make sure you have both installed.\n\nI use `pyenv <https://github.com/pyenv/pyenv#simple-python-version-management-pyenv>`_ to\nmanage multiple Python versions and I described my workspace setup on this article:\n`The definitive guide to setup my Python workspace\n<https://medium.com/@henriquebastos/the-definitive-guide-to-setup-my-python-workspace-628d68552e14>`_\n\nYou can submit pull requests and issues for discussion. However I only\nconsider merging tested code.\n\n\nLicense\n=======\n\nThe MIT License (MIT)\n\nCopyright (c) 2017 Henrique Bastos <henrique at bastos dot net>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Strict separation of settings from code.",
    "version": "3.6",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "9cbcf1aea2ad3d12be6be578b64bd4ac",
                "sha256": "6cf502dc963a5c642ea5ead069847df3d916a6420cad5599185de6bab11d8c2e"
            },
            "downloads": -1,
            "filename": "python_decouple-3.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9cbcf1aea2ad3d12be6be578b64bd4ac",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 9881,
            "upload_time": "2022-02-02T19:25:29",
            "upload_time_iso_8601": "2022-02-02T19:25:29.850864Z",
            "url": "https://files.pythonhosted.org/packages/3a/20/c1b1533a02946c728f7b6e1d45ed3216c5eef4c8e8777d0db06e361f11e4/python_decouple-3.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "70dae7267638c98181f89e9a1f32a913",
                "sha256": "2838cdf77a5cf127d7e8b339ce14c25bceb3af3e674e039d4901ba16359968c7"
            },
            "downloads": -1,
            "filename": "python-decouple-3.6.tar.gz",
            "has_sig": false,
            "md5_digest": "70dae7267638c98181f89e9a1f32a913",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 9547,
            "upload_time": "2022-02-02T19:25:31",
            "upload_time_iso_8601": "2022-02-02T19:25:31.789818Z",
            "url": "https://files.pythonhosted.org/packages/ad/90/b49583e8dfb94c3b699070701ae6a8415de6c0445c1df9c11f912e051316/python-decouple-3.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-02-02 19:25:31",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "henriquebastos",
    "github_project": "python-decouple",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "mock",
            "specs": [
                [
                    "==",
                    "2.0.0"
                ]
            ]
        },
        {
            "name": "pytest",
            "specs": [
                [
                    "==",
                    "3.2.0"
                ]
            ]
        },
        {
            "name": "tox",
            "specs": [
                [
                    "==",
                    "2.7.0"
                ]
            ]
        },
        {
            "name": "docutils",
            "specs": [
                [
                    "==",
                    "0.14"
                ]
            ]
        },
        {
            "name": "Pygments",
            "specs": [
                [
                    ">=",
                    "2.7.4"
                ]
            ]
        },
        {
            "name": "twine",
            "specs": []
        }
    ],
    "tox": true,
    "lcname": "python-decouple"
}
        
Elapsed time: 0.01564s