[Python] python-dotenv
python-dotenv
How did I encounter this?
While implementing DB into GTPS project, I was faced with the fact that the credential to the DB is exposed into the python script. In order to hide them out of the script, I found a way. The basic concept is that the credential should be separated from the project code, stored in a separate file. More importantly, the file should not be exposed, which means it should not be present in my Git repository.
There is a library called python-dotenv. This allows to add what's in my .env file into the list of environment variables. After load_dotenv(), the values should be accessed as environment variable.
Syntax & Example
<.env file>
DB_USER=root
DB_PASSWORD=your_password
<project script>
from dotenv import load_dotenv
import os
# Load the .env file
load_dotenv()
# Access environment variables
db_user = os.getenv('DB_USER')
db_password = os.getenv('DB_PASSWORD')
print(f"User: {db_user}, Password: {db_password}")
Note:
After this, the .env file should be added into .gitignore file.
Comments
Post a Comment