LoginSignup
25
14

More than 5 years have passed since last update.

HerokuアプリからGoogleスプレッドシートを操作する際、認証情報を環境変数から読み込みたい

Last updated at Posted at 2018-08-30

目的

Google Sheets APIのPythonクライアントライブラリ『gspread』を使って、Heroku上のPythonスクリプトからGoogleスプレッドシートを操作したい

問題

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name('gspread-april-2cd … ba4.json', scope)

gc = gspread.authorize(credentials)

wks = gc.open("Where is the money Lebowski?").sheet1
  • Heroku上のPythonスクリプトで上記手順を実行するには、『認証に必要な情報が書かれたJSONファイル』をHerokuにデプロイする必要がある
  • しかし、秘密情報である『認証に必要な情報が書かれたJSONファイル』をHerokuに置きたくない
  • 認証に必要な情報はHerokuの環境変数から読み込みたい

という状況で、以下の記事を見つけた。

PythonのHerokuアプリケーションからGoogle Spread Sheetの読み書き

この記事では、環境変数とテンプレートから『認証に必要な情報が書かれたJSONファイル』を生成しているが、もっとシンプルな方法はないのか。

解決策

credentials変数を生成する際に、from_json_keyfile_nameではなく、from_json_keyfile_dictを使う。
from_json_keyfile_dictならば、認証に必要な情報をPython辞書オブジェクトで渡せる。

oauth2client.service_account module — oauth2client 4.1.2 documentation

認証に必要な情報をJSONファイルで渡す必要がなくなるので、『認証に必要な情報が書かれたJSONファイル』をHerokuに置く必要もなくなる。

コード

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

# 辞書オブジェクト。認証に必要な情報をHerokuの環境変数から呼び出している
credential = {
                "type": "service_account",
                "project_id": os.environ['SHEET_PROJECT_ID'],
                "private_key_id": os.environ['SHEET_PRIVATE_KEY_ID'],
                "private_key": os.environ['SHEET_PRIVATE_KEY'],
                "client_email": os.environ['SHEET_CLIENT_EMAIL'],
                "client_id": os.environ['SHEET_CLIENT_ID'],
                "auth_uri": "https://accounts.google.com/o/oauth2/auth",
                "token_uri": "https://oauth2.googleapis.com/token",
                "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
                "client_x509_cert_url":  os.environ['SHEET_CLIENT_X509_CERT_URL']
             }

credentials = ServiceAccountCredentials.from_json_keyfile_dict(credential, scope)

gc = gspread.authorize(credentials)

wks = gc.open('Where is the money Lebowski?').sheet1

その他

  • Herokuの環境変数にPRIVATE KEYを登録する際は、改行したうで、改行コードを消す。

hkmdvQ2feNjbklxE2MLRXrsDg\nVCCHmuITKnfFfrrXvUrkQLzVt

hkmdvQ2feNjbklxE2MLRXrsDg
VCCHmuITKnfFfrrXvUrkQLzVt

25
14
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
25
14