[Django]-Where to store api key in Django

6👍

There are two ways to do this.

One way is to have a local_settings.py file that’s imported in the main settings.py file and put into .gitignore so it’s not in git. Some people however think this isn’t good practice, because it might tempt to put complex things in there that aren’t in VCS, so people effectively have different environments. I however am fine with it.

try:
    from local_settings import *
except ImportError:
    pass  # No local_settings file

The other way (recommended by dislikers of the first way) is by setting it via environment variables, and reading these in settings.py.

MONGO_API_KEY = os.environ['MONGO_API_KEY']

You’d then have to pass the environment variable somehow though. E.g. via uwsgi’s environ setting, or by setting it in your bash with export, or via another way.

1👍

I would load it in the settings file from an environment variable. Have a look at the Django Settings

👤t_io

0👍

One alternative is to use the library django-fernet-fields that uses the library cryptography.

The usage is very simple. In your model you need to add a new field:

from django.db import models
from fernet_fields import EncryptedTextField

class MyModel(models.Model):
    apikey = EncryptedTextField()

By default, the field is going to be encrypted using the SECRET_KEY from your settings. So if you change it or lose it, you will not be able to access your data.

For better security, you can save your SECRET_KEY as an environment variable, and then pass it to the settings file.

import os

SECRET_KEY = os.environ.get('APP_SECRET_KEY', 'unsafe-secret-key')

django-fernet-fields

👤mcrrnz

0👍

Quick answer:

  1. Store in .env
  2. Read in settings.py

Leave a comment