꿈을 향해 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:32Credentials (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.
A .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.
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
'데이터 사이언스 공부' 카테고리의 다른 글
Pandas - json_normalize 문제 총 정리 (0) | 2022.04.02 |
---|---|
복잡한 JSON 파일 쉽게 처리하기 - 파이썬 (How to flatten complex JSON file in Python) (0) | 2022.04.02 |
Webhook vs API 차이 (0) | 2022.01.26 |
Connect MySQL database with Python (0) | 2021.12.22 |
초간단 웹 스크레이핑 / 웹 크롤링 (크롬 익스텐션 - Web Scraper) (2) | 2020.09.09 |