.env file is commonly used for configuration.
Python also has 3rd party library for this.
Installation
It can be installed by pip.
$ pip install python-dotenv
Create .env File
.env file consists of key-value pair.
# .env
TEST=test
TEST_URL=${TEST}.com
You can expand the config using ${} syntax.
TEST1="test
string"
TEST2="Test\nString"
You can use a value as multiple lines using escape characters and quotes.
It is also possible to use other escape characters like \t, \r, \\, \', \", etc.
Using with load_dotenv
python-dotenv module has load_dotenv() function.
This function registers the configuration into environment variables.
import os
from dotenv import load_dotenv
load_dotenv()
print(os.environ['TEST'])
# test
print(os.environ['TEST_URL'])
# test.com
load_dotenv() function has override parameter and its default value is True.
load_dotenv(override=True)
It means overriding system environment variables if the same configuration exists.
In other words, if you set this to False, system environment variables are used if the same configuration exists.
Using with dotenv_values
dotenv_values() function returns ordered dictionary with configuration.
import os
from dotenv import dotenv_values
config = dotenv_values('.env')
print(config['TEST'])
# test
print(config['TEST_URL'])
# test.com
'Python' 카테고리의 다른 글
[Python] Using PostgreSQL (0) | 2022.05.19 |
---|---|
[Python] Using Telegram Bot API (0) | 2022.05.13 |
[Python] Pandas Course on Kaggle - 6 (0) | 2022.01.22 |
[Python] Pandas Course on Kaggle - 5 (0) | 2022.01.21 |
[Python] Pandas Course on Kaggle - 4 (0) | 2022.01.20 |
댓글