docs
  • Overview
  • 🐍 PYTHON
    • Type Hints
    • PEP8 Style Guide for Python Code
    • 🏡Pipenv
    • Pathlib
  • 🕸Django
    • 🗄models
      • 🎯Best Practices
      • 🚦Django Signals
    • ⚙️ settings
    • DRF
      • Serializer
      • Authentication
      • Permissions
      • Viewsets
    • Testing
      • Faker and Factory Boy
    • 🧪Test Coverage
    • 💦Python-Decouple
    • Django Tips:
    • 💾Django ORM Queryset
    • Custom Exceptions
    • Celery
    • Resources
  • Deploy
    • 🚀Django Deployment
    • 🔒Setup SSL Certificate
  • 💾Database
    • MongoDB
  • 🛠️DevOps
    • 🖥Scripting
      • A First Script
      • Loops
      • Test
      • Variables
      • External programs
      • Functions
    • Command Line Shortcuts
    • Basic Linux Commands
    • 🎛Microservices
    • 🐳Docker
      • Docker Commands
      • Docker Compose
      • Django project
    • Kubernates
  • 📝Software IDE
    • EditorConfig
    • Linters
    • VsCode
Powered by GitBook
On this page
  • Python Decouple
  • Install:
  • Import the config object:
  • Retrieve the configuration parameters:
  • For Allowed Host:
  • Postgres database config:

Was this helpful?

  1. 🕸Django

💦Python-Decouple

Python Decouple

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:

  1. store parameters in ini or .env files;

  2. define comprehensive default values;

  3. properly convert values to the correct data type;

  4. 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.

Install:

pip install python-decouple
pipenv install python-decouple

Then use it on your settings.py.

Import the config object:

from decouple import config, Csv

Retrieve the configuration parameters:

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

For Allowed Host:

ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='127.0.0.1', cast=Csv())

Postgres database config:

settings.py
DATABASES = {
    "default": {
        "ENGINE": config("ENGINE"),
        "NAME": config("DATABASE"),
        "USER": config("USER"),
        "PASSWORD": config("PASSWORD"),
        "HOST": config("HOST", "localhost"),
        "PORT": config("PORT", "5432"),
    }
}

Decouple supports both .iniand .env files.

DEBUG=True
ALLOWED_HOST='.localhost,'
SECRET_KEY=ARANDOMSECRETKEY
ENGINE=django.db.backends.postgresql
DATABASE=<dbname>
USER=<db_username>
PASSWORD=<db_password>
HOST=db
PORT=5432
# This is comment 
[settings]
DEBUG=True
ALLOWED_HOST='.localhost,'
SECRET_KEY=ARANDOMSECRETKEY
ENGINE=django.db.backends.postgresql
DATABASE=<dbname>
USER=<db_username>
PASSWORD=<db_password>
HOST=db
PORT=5432
PreviousTest CoverageNextDjango Tips:

Last updated 4 years ago

Was this helpful?