LoginSignup
2
4

More than 3 years have passed since last update.

python-dotenvを使い環境変数を管理

Posted at

python-dotenvを使い環境変数を管理

初めに

API_KEYなどPythonファイルにベタ書きだと使い勝手が悪いため
python-dotenvを使い環境変数を設定する

from datetime import timedelta

import pandas as pd
import tweepy

API_KEY = "xxx"
API_SECRET_KEY = "xxx"
ACCESS_TOKEN = "xxx"
ACCESS_TOKEN_SECRET = "xxx"


def twitter_api() -> tweepy.API:
    auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    return tweepy.API(auth)

python-dotenvバッケージをインストール

$ pip install python-dotenv

使い方

.envファイル作成

API_KEY = "xxx"
API_SECRET_KEY = "xxx"
ACCESS_TOKEN = "xxx"
ACCESS_TOKEN_SECRET = "xxx"

settigs.py作成
.envからデータを読み込む

import os
from os.path import dirname, join

from dotenv import load_dotenv

load_dotenv(verbose=True)

dotenv_path = join(dirname(__file__), ".env")

API_KEY = os.environ.get("API_KEY")
API_SECRET_KEY = os.environ.get("API_SECRET_KEY")
ACCESS_TOKEN = os.environ.get("ACCESS_TOKEN")
ACCESS_TOKEN_SECRET = os.environ.get("ACCESS_TOKEN_SECRET")

元Pythonファイル変更

from datetime import timedelta

import pandas as pd
import tweepy

from settings import API_KEY, API_SECRET_KEY, ACCESS_TOKEN, ACCESS_TOKEN_SECRET


def twitter_api() -> tweepy.API:
    auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    return tweepy.API(auth)

何がいいか

環境変数が散らばると参照がし難い、セキュリティ的にも良くない
python-dotenを使うと.envに集約できる

2
4
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
2
4