django-pgconninfo
picks up PostgreSQL connection configuration from
environment variables and construct a map suitable for assignment to DATABASES
in Django settings. This code can handle Heroku, Amazon Elastic Beanstalk,
PostgreSQL service files (.pg_service.conf
), libpq
environment variables,
and PostgreSQL password files (~/.pgpass
).
The idea of pgconninfo
is to avoid hardcoded database location and credentials
in source code. This is desirable for several reasons:
-
Credentials don't belong to source code or version control repositories.
-
Switching from development to production without code change.
-
Major cloud services already adopted environment variables for configuration.
For more on configuration through the environment, check the twelve-factor app.
You can install django-pgconninfo via Pypi:
pip install django-pgconninfo
To use the default engine (psycopg2):
from pgconninfo import pg_conninfo
DATABASES = {
'default': pg_conninfo()
}
or, to use an alternative engine, explicitly state the engine class:
from pgconninfo import pg_conninfo
DATABASES = {
'default': pg_conninfo('django.contrib.gis.db.backends.postgis')
}
pg_conninfo
can configure the database connection using any of the following
environment variables:
-
DATABASE_URL
This is a standard PostgreSQL environment variable and is used by Heroku. The format of this variable is described in PostgreSQL's documentation
-
RDS_HOSTNAME
,RDS_PORT
,RDS_DB_NAME
,RDS_USERNAME
, andRDS_PASSWORD
These are the environment variables used by AWS Elastic Beanstalk and are documented in their developer guide
-
PGSERVICE
, and optionallyPGSERVICEFILE
PostgreSQL's documentation describes the location and format of connection service files and the configuration keywords to be used in them
-
PGHOST
,PGPORT
,PGDATABASE
,PGUSER
, andPGPASSWORD
The
libpq
environment variables are described in PostgreSQL's documentation
In addition to environment variables, pg_conninfo
also checks the password
file if no
password was given elsewhere.