From here, we add all database info as text:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
Is it a secure way? Is there any way to save this data as Encrypted data?
Additional security topicsMake sure that your Python code is outside of the web server's root. This will ensure that your Python code is not accidentally served as plain text (or accidentally executed). Take care with any user uploaded files. Django does not throttle requests to authenticate users.
Django is a solid framework when it comes to security. However, there are a couple of minor issues. First, even though querysets prevent SQL injection by default, functions still exist that allow developers to create raw SQL queries.
Default settings These defaults live in the module django/conf/global_settings.py . Here's the algorithm Django uses in compiling settings: Load settings from global_settings.py . Load settings from the specified settings file, overriding the global settings as necessary.
django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Affected versions of this package are vulnerable to Cross-site Scripting (XSS) attacks. Autoescaping of HTML was disabled by default in the technical 500 debug page template.
It isn't secure, anyone with access to your source control now has access to your database.
The two main methods of storing sensitive data are either with environment variables or via a json file
Excerpted from Settings - Hiding secret data using a JSON file. The original authors were Antoine Pinsard and fredley. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 942 and example ID: 8734.
Hiding secret data using a JSON file
When using a VCS such as Git or SVN, there are some secret data that must never be versioned (whether the repository is public or private).
Among those data, you find the SECRET_KEY
setting and the database password.
A common practice to hide these settings from version control is to create a file secrets.json
at the root of your project (thanks "Two Scoops of Django" for the idea):
{
"SECRET_KEY": "N4HE:AMk:.Ader5354DR453TH8SHTQr",
"DB_PASSWORD": "v3ry53cr3t"
}
And add it to your ignore list (.gitignore
for git):
*.py[co]
*.sw[po]
*~
/secrets.json
Then add the following function to your settings
module:
import json
import os
from django.core.exceptions import ImproperlyConfigured
with open(os.path.join(BASE_DIR, 'secrets.json')) as secrets_file:
secrets = json.load(secrets_file)
def get_secret(setting, secrets=secrets):
"""Get secret setting or fail with ImproperlyConfigured"""
try:
return secrets[setting]
except KeyError:
raise ImproperlyConfigured("Set the {} setting".format(setting))
Then fill the settings this way:
SECRET_KEY = get_secret('SECRET_KEY')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgres',
'NAME': 'db_name',
'USER': 'username',
'PASSWORD': get_secret('DB_PASSWORD'),
},
}
Credits: Two Scoops of Django: Best Practices for Django 1.8, by Daniel Roy Greenfeld and Audrey RoyGreenfeld. Copyright 2015 Two Scoops Press (ISBN 978-0981467344)
Excerpted from Settings - Using Environment variables to manage Settings across servers. The original authors were sudshekhar, ssice and NBajanca. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 942 and example ID: 3580.
Using Environment variables to manage Settings across servers
Using environment variables is a widely used way to setting an app's config depending on it environment, as stated in The Twelve-Factor App.
As configurations are likely to change between deployment environments, this is a very interesting way to modify the configuration without having to dig in the app's source code, as well as keeping secrets outside the application files and source code repository.
In Django, the main settings are located as settings.py
in your project's folder. As it is a simple Python file, you can use Python's os
module from the standard library to access the environment (and even have appropriate defaults).
import os
SECRET_KEY = os.environ.get('APP_SECRET_KEY', 'unsafe-secret-key')
DEBUG = os.environ.get('DJANGO_DEBUG', "True") == "True"
ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', '').split()
DATABASES = {
'default': {
'ENGINE': os.environ.get('APP_DB_ENGINE', 'django.db.backends.sqlite3'),
'NAME': os.environ.get('DB_NAME', 'db.sqlite'),
'USER': os.environ.get('DB_USER', ''),
'PASSWORD': os.environ.get('DB_PASSWORD', ''),
'HOST': os.environ.get('DB_HOST', None),
'PORT': os.environ.get('DB_PORT', None),
'CONN_MAX_AGE': 600,
}
}
With Django you can change your database technology, so that you can use sqlite3 on your development machine (and that should be a sane default for committing to a source control system). Although this is possible it is not advisable:
Backing services, such as the app’s database, queueing system, or cache, is one area where dev/prod parity is important. (The Twelve-Factor App - Dev/prod parity)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With