LoginSignup
61
58

More than 5 years have passed since last update.

pythonでGoogle Spread Sheetをいじる(OAuth)

Last updated at Posted at 2016-04-11

環境

  • Mac OSX(El Capitan)
  • Python 2.7

準備

Google Drive APIの発行

プロジェクトの作成

  • プロジェクトが無い場合は右上のExampleの箇所から新規プロジェクトの作成を行います

スクリーンショット 2016-04-11 22.46.14.png

  • プロジェクト名とIDを決める事が出来ます

スクリーンショット 2016-04-11 22.45.20.png

API

スクリーンショット 2016-04-11 22.29.31.png

  • APIを有効にしたら左の認証情報を選択し、認証情報を作成 -> サービスアカウントキーを選択します (サービスアカウントが無い場合は作成して下さい)

スクリーンショット 2016-04-11 22.30.48.png

  • JSONとP12形式が選択可能ですが、ここではJSONを利用します

スクリーンショット 2016-04-11 22.36.07.png

  • 完了するとJSONファイルが自動的にダウンロードされます

スプレッドシート側の共有設定

  • 使用するスプレッドシートの右上にある共有ボタンを押し、ダウンロードしたJSONファイルに記載されているclient_emailの欄のアドレスを入力します

スクリーンショット 2016-04-11 22.53.04.png

  • id

urlのhttps://docs.google.com/spreadsheets/d/***********/edit
アスタリスク部分がidになります

Python

ライブラリのインストール

  • ライブラリ
    • oauth2client
      sudo pip install --upgrade oauth2client --ignore-installed six
    • gdata (google正規: 今回は使わない)
      sudo pip install gdata --ignore-installed six
    • gspread (こちらの方が便利そうなので今回はこっちを使用します)
      sudo pip install gspread --ignore-installed six

※ El Capitanでは System Integrity Protection (SIP)のせいでpipのinstallが失敗するので、--ignore-installed sixを最後に付けてます

Code

  • 以前はSignedJwtAssertionCredentialsクラスが使用されていたのですが、2016/02にライブラリのアップデートがありServiceAccountCredentialsを使うようになりました

import os
import gspread
from oauth2client.service_account import ServiceAccountCredentials

def main():
    scope = ['https://spreadsheets.google.com/feeds']
    doc_id = 'Your doc id'
    path = os.path.expanduser("Path of json file")

    credentials = ServiceAccountCredentials.from_json_keyfile_name(path, scope)
    client = gspread.authorize(credentials)
    gfile   = client.open_by_key(doc_id)
    worksheet  = gfile.sheet1
    records = worksheet.get_all_values()

    for record in records:
        print(record)

if __name__ == '__main__':
    main()
61
58
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
61
58