DEV Community

Cover image for Environment Variables in Django
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on • Originally published at Medium

Environment Variables in Django

One way of securing your secret keys from external viewers and codebase is to use environment variables.

In Python, you can use the os.getenv('THE_KEY') or os.environ.get('THE_KEY').
For example, when working in Python, you can change tell Django to search for the value of the SECRET_KEY.

SECRET_KEY = os.getenv("SECRET_KEY") 
# or
SECRET_KEY = os.environ.get("SECRET_KEY") 
Enter fullscreen mode Exit fullscreen mode

These lines will lead to software failure if there is no SECRET_KEY variable in the project's .env file.

To avoid that, you can pass as a second argument a default value.

SECRET_KEY = os.getenv(
    "SECRET_KEY", "django-insecure-r(6dd3yaw_05m5kxki1vb^r6v@x^-g#zi_to7487*!)08oxwf)"
)
Enter fullscreen mode Exit fullscreen mode

These methods are quite useful if you are looking to use env vars in Django. Anyway, you can also check django-environ a Python package that allows you to use the Twelve-factor methodology to configure your Django application with environment variables.

Article posted using bloggu.io. Try it for free.

Top comments (0)