How to use environment variables in Python natively?
Why use a .env when working on a project?
You’re trying to work on your side project in python, and you have come to the point where you are trying to refactor your code, and you realize it’s not a great idea to have all your configuration variables out there in the open. According to the manifesto, you store them an env variable as they can scale up as the app expands over time, and they are straightforward to change between deployments without changing the code.
Using python natively.
As a beginner, I try to limit my use of libraries and figure out native python ways to solve any issues. Let me introduce another great feature of python using a config parser.
In Layman’s Terms:
Config parser => Config Files.
This module lets you manage config files for your application.
In Python Terms:
“This module provides the ConfigParser class, which implements a basic configuration language that provides a structure similar to what’s found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end-users easily.”
Step 1. Create the .env file.
The structure of the .env consists of sections that must be led with a [section] header as like this:
[heroku]user = ***password=***database=****cursor = *****
And must be followed by either an = or :
Step 2: Import into your Database File and config the environment.
Import configpaserConfig = configparser.conconfig.read(‘env’)
Step 3: Connect your App database to the .env file. In this example, I’m working on connecting a SQL database with my flask app, which is what the app variable is.
[‘local’] = section header
[‘user’] = key.
app.config[‘MYSQLUSER’] = config[‘local’][‘user
That’s all folks!
I’m always looking to meet more engineers in my field, find me on Linkedin and let’s connect!