はじめに
外部に公開したくないAPIキーなどの情報はgit管理の対象から外し、.env
ファイルに記載した環境変数として使用したいです。
環境
Python 3.12.2
モジュールのインストール
次のコマンドでインストールします。
pip install python-dotenv
envファイルの準備
サンプルとして次のようにSAMPLE_KEY
を記載した.env
ファイルを準備します。
.env
SAMPLE_KEY='hello_test_key'
.envファイルをgit管理の対象から外す
.env
ファイルはgit管理の対象としたくないので、次のように.gitignore
ファイルを作成する。
.gitignore
.env
envファイルの読み込み
main.py
# dotenvの読み込み
from dotenv import load_dotenv
import os
# .envファイルの読み込み
load_dotenv()
# 環境変数の取得
sample_key = os.getenv('SAMPLE_KEY')
print(sample_key)
上記ソースを実行すると、.env
ファイルに記載した環境変数が出力される事が確認できた。
ログ
hello_test_key