꿈을 향해 on my way

Using .env Files for Environment Variables in Python Applications 본문

데이터 사이언스 공부

Using .env Files for Environment Variables in Python Applications

박재성 2021. 12. 22. 04:32

Credentials (for example, DB_USER (Dbeaver user_id) and DB_PASS (Dbeaver user_password) below) are sensitive information and should be stored securely. Using a .env file will enable you to use environment variables for local development without polluting the global environment namespace. It will also keep your environment variable names and values isolated to the same project that utilizes them.

 

Nearly every programming language has a package or library that can be used to read environment variables from the .env file instead of from your local environment. For Python, that library is python-dotenv

 

1. Install “python-dotenv” library

Open your terminal and type pip install python-dotenv. If you already have it, just skip this.

 

2. Change directory to your project root directory

Project root directory is where your python/ jupyter notebook is located. The reason why changing directory is because python-dotenv (which we will use later to load environment variables) will look for the .env file in the current working directory or any parent directories.

change your directory where you want to create .env file
3. Create ‘.env’ file in your project root directory

.env file is a text file containing key value pairs of all the environment variables required by your application. This file is included with your project locally but not saved to source control so that you aren't putting potentially sensitive information at risk.

Open your terminal and type  vi .env
You are in  .env  file. Write credentials and hit  :wq
 

4. Load the credentials

import os
from dotenv import load_dotenv
load_dotenv()

db_user = os.environ.get("DB_USER") 
db_password = os.environ.get("DB_PASS")

*If you are using git, make sure to add .env to .gitignore

Reference

https://pypi.org/project/python-dotenv/

https://dev.to/jakewitcher/using-env-files-for-environment-variables-in-python-applications-55a1

Comments