Using .env Files for Environment Variables in Python Applications. What, When, How and Why?

Saketh G
4 min readOct 7, 2022
Python code image
Photo by Artturi Jalli on Unsplash

Any kind of application that we develop uses data to perform various tasks, such as performing internal logic, configuration of the project, connecting to a database or any cloud service, sending data to an API or receiving data from an API, etc. The question is, from where does the program receives this data. Obviously from the program that we write right? But is this way provide data to the application via program is always recommended? If not, why? What are the other ways that we could employ to achieve this? In this article we are going to answer such questions. But before diving down into the topic further, let us look at some example code snippets.

Example 1 : Establishing connection to a MySQL database

mydb = mysql.connector.connect(
host="localhost",
user="admin",
password="123456"
)

In the above example, we are trying to connect to a MySQL database using python. In order to achieve this, the program requires three data values, i.e., host, username, and password, which we are providing in the code itself.

Example 2 : Reading data from a table

mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()

--

--

Saketh G
0 Followers

Co-Founder @ pickupsmart | Studying M.Sc. Computer Science from TUM | Learn programming together | Support @ https://codesmartwithsaketh.medium.com/membership