0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【基礎確認】pythonのdotenvモジュール

Posted at

はじめに

LangChainとLangGraphによるRAG・AIエージェント[実践]入門
を読んでいて、10章で躓いたので、初心に戻って、一つずつ紐解いて学習することにしました。
今回のテーマは「dotenv」モジュール

前回までの投稿

  1. 必要なライブラリとモジュールをインポートする
    【基礎確認】pythonのoperatorモジュール
    【基礎確認】pythonのtypingモジュール

事前作業

python実行ディレクトリに.envというファイルを作成し

API_KEY=i0NT1K4m-ls5j0i4Q-ic1A6bMAbwNm5KY4

というキーを保存しておく。
(記載しているキーはダミー)

サンプルコード

sample.py
from dotenv import load_dotenv
import os

# .envファイルから環境変数を読み込む
load_dotenv()

# 環境変数を取得して表示
api_key = os.getenv("API_KEY")
print(f"API Key: {api_key}")

解説

dotenvモジュールを使用して.envファイルから環境変数を読み込み、その値を取得する。

  1. from dotenv import load_dotenvで、dotenvモジュールからload_dotenv関数をインポート。
  2. import osで、環境変数を取得するためのosモジュールをインポート。
  3. load_dotenv()を呼び出して、.envファイルから環境変数を読み込む。
  4. os.getenv("API_KEY")を使用して、"API_KEY"という名前の環境変数の値を取得。
  5. 取得した値を表示。
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?