Environment Variables in Django
I am a software engineer with 4 years of professional experience, currently specializing in full-stack development.
I work a lot with HTML, CSS, JavaScript, and Python and regularly use React, Vue, and Django to build single-page applications and marketing landing pages.
I also work with React Native to build mobile applications with optimized experiences and for businesses who want to ship products in the market quickly.
Currently, I am a part of a team of 8 as a full-stack engineer where I focus on accessibility, component-driven approaches, and building systems that can scale with ease.
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")
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)"
)
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.




