As per the twelve-factor app methodology it is important to store config outwith the program that can be injected in at runtime.
Not only does this keep sensitive information secure such as our passwords and API keys. Additionally it allows us to make us of a single settings.py
file to load either out local or production environments variables.
There are many options for doing this, but the Django community seems to like environs as it comes with additional Django support built-in.
To install it via pip:
python3 -m pip install "environs[django]"==9.5.0
Then add these three lines to the top of yout project/settings.py
file:
from environs import Env
env = Env()
env.read_env()
Database config using environment variables
An example use case is configuring our project to use a SQLite database locally, but a PostgreSQL database in production.
The environs package comes installed with dj-database-url. A package that allows us to set a DATABASE_URL
that is utilised by most PaaS providers.
With a very small amount of code in our project/settings.py
file, we can configure our project to try to access a DATABASE_URL
environment variable. If it exists it will be used and our project will access our 'production' PostgreSQL database, if one can't be found then it will default to SQLite, e.g. locally.
Change the default 'DATABASES' section in your settings.py
file from this:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
To this:
DATABASES = {
"default": env.dj_db_url("DATABASE_URL", default="sqlite:///db.sqlite3"),
}
Configuring as PostgreSQL database in Django
In order to use a PostgreSQL database we need an adapter that allows Python to communicate with a PostgreSQL database. The community seems to favour Pyscopg for this.
If you are on a Mac like me, you will also need to have installed PostgreSQL via homebrew first:
brew install postgresql
python3 -m pip install "psycopg[binary]"==3.1.8
Top comments (0)