Python クイックスタート

みるくあいらんどっ! > 和訳 > google関係 > Drive API > api > v3 > クイックスタート


  • この記事は、Google Drive™ APIに関する記事を和訳したものです。
  • 原文: Python Quickstart
  • 元記事のライセンスは CC-BYで、この和訳記事のライセンスは CC-BYです。
  • 自己責任でご利用ください。
  • 和訳した時期は 2019年6月ころです。

Drive APIにリクエストを行う単純な Pythonコマンドラインアプリケーションを作成するには、このページの残りの部分で説明されている手順を完了します。

前提条件

このクイックスタートを実行するには、次のものが必要でしょう:

  • Python 2.6以上
  • pipパッケージ管理ツール
  • Google Driveが有効である Googleアカウント

Step 1: Drive APIをオンにする

新しい Cloud Platform projectを作成するためにこのボタンをクリックし、Drive APIを自動的に有効にします:

Drive APIを有効にする

ダイアログが表示されたら、DOWNLOAD CLIENT CONFIGURATIONをクリックし、あなたの作業ディレクトリにファイル credentials.json を保存します。

Step 2: Google Client Libraryをインストールする

pipを使用してライブラリをインストールするには、次のコマンドを実行します:

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

他のインストールオプションについては、ライブラリのインストールページを参照してください。

Step 3: サンプルをセットアップする

あなたの作業ディレクトリに、quickstart.py と名付けられたファイルを作成し、次のコードをコピーします:

drive/quickstart/quickstart.py
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    results = service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])

    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))

if __name__ == '__main__':
    main()

Step 4: サンプルを実行する

次のコマンドを使用してサンプルを実行します:

python quickstart.py
  1. サンプルは、あなたのデフォルトブラウザにて新しいウインドウあるいはタブを開こうとするでしょう。 もしこれが失敗したならば、コンソールから URLをコピーし、手動であなたのブラウザにてそれを開きます。

    もし、まだあなたの Googleアカウントにログインしていなければ、ログインを求められるでしょう。 もし、複数の Googleアカウントにログインしているならば、認証のために使用する 1つのアカウントを選択するよう求められるでしょう。

  2. Acceptボタンをクリックします。
  3. サンプルは自動的に進行するでしょう、そして、ウインドウ/タブを閉じても良いです。

ノート

  • 認証情報は、ファイルシステム上に格納されるので、以降の実行では認証を求められないでしょう。
  • この例の認証フローは、コマンドラインアプリケーションのためにデザインされています。 ウェブアプリケーションにて認証を実行する方法については、Using OAuth 2.0 for Web Server Applicationsを参照してください。

参考文献

トラブルシューティング

このセクションでは、このクイックスタートを実行しようとしたときに遭遇するかもしれない、幾つかの一般的な問題について説明し、可能な解決策を提案します。

AttributeError: 'Module_six_moves_urllib_parse' object has no attribute 'urlparse'

このエラーは、sixモジュール(このライブラリの依存関係)のデフォルトインストールが、pipがインストールされたものより前に読み込まれる場合に、Mac OSX上で発生する可能性があります。 この問題を解決するには、pipのインストール場所を PYTHONPATHシステム環境変数に追加します:

  1. 次のコマンドを用いて pipのインストール場所を決定します:

    pip show six | grep "Location:" | cut -d " " -f2
    
  2. あなたの ~/.bashrcファイルに以下の行を追加し、<pip_install_path>を上記で決定した値に置換します:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. 次のコマンドを使用して、開いているターミナルウインドウにて、あなたの ~/.bashrcファイルをリロードします:

    source ~/.bashrc
    

TypeError: sequence item 0: expected str instance, bytes found

このエラーは httplib2のバグによるもので、最新バージョンにアップグレードすることでそれを解決する必要があります:

pip install --upgrade httplib2

Cannot uninstall 'six'. It is a distutils installed project...

pip installコマンドを実行するとき、次のエラーを受け取るかもしれません:

Cannot uninstall 'six'. It is a distutils installed project and thus we
cannot accurately determine which files belong to it which would lead to
only a partial uninstall.

これは、既にインストールされている sixパッケージをアップグレードしようとするとき、Mac OSX上で発生する可能性があります。 この問題を回避するには、Step 2にリストされた pip installコマンドに、フラグ --ignore-installed sixを追加することができます。

This app isn't verified.

機密性の高いユーザデータへのアクセスを提供するスコープをリクエストしている場合、ユーザに表示される OAuth同意画面に、警告 "This app isn't verified" が表示されるかもしれません。 これらのアプリケーションは、その警告および他の制限を取り除くための検証プロセスを、最終的には通過しなければなりません。 開発段階では、Advanced > Go to {Project Name} (unsafe) をクリックすることによって、この警告を追加し続けることができます。