1
2

はじめに

外部に公開したくない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
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2