LoginSignup
3
4

More than 5 years have passed since last update.

PythonでGoogle ColaboratoryとGoogle Driveのファイルのやりとりする(2)

Last updated at Posted at 2018-05-06

2.必要なライブラリのインストール

Step 2: Install the Google Client Library
Run the following command to install the library using pip:
pip install --upgrade google-api-python-client

Colaboratoryに関しては最初からインストール済なので不要だが、
他の端末でGoogle DriveのAPIを使用する場合は必要。

install
! pip install --upgrade google-api-python-client

3.serviceの作成(quickstart.pyの実行)

下記のコードにより、前回の記事で作成した'client_secret.json'をColaboratory上にアップロードする。

upload
#file upload dialog
import google.colab.files as ggl
fname=ggl.upload()
print(fname)

小技として、以下のようにするとアップロードしたファイルの名前をfnameと定義できる。

printname
#print name
fname = [k for k in fname.keys()][0]
print(fname)

そして、名前の変更は以下の通り。

rename
#change the token name
import os
os.rename(fname,'client_secret.json')

チュートリアルには
Step 3: Set up the sample
Create a file named quickstart.py in your working directory and copy in the following code:
とあり、quickstart.pyを作成して、Colaboratoryにアップロードしたうえで、

quickstart
run quickstart.py --noauth_local_webserver

を行うのが方法がオーソドックスな方法。

ファイルを作ったり、そのコードをアップロードするのが手間がかかるので、
下記のコードによっても同じことができます。

service
import sys
from oauth2client import file, client, tools
from oauth2client.tools import argparser, run_flow
from apiclient.discovery import build
from httplib2 import Http
def service():
    sys.argv=[]
    args = argparser.parse_args()
    args.noauth_local_webserver = True

    SCOPES = 'https://www.googleapis.com/auth/drive'
    store = file.Storage('./credentials.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
        creds = tools.run_flow(flow, store,args)
    service = build('drive', 'v3', http=creds.authorize(Http()))
    return service
service=service()

注1)パラメータの設定
クラウド上のColaboratoryではない端末である、ローカルPCで認証するため、
パラメータ "--noauth_local_webserver"を設定する必要があります。
下記のコードはよくみると、頑張ってこのパラメータが渡されるようにしています。
注2)権限の設定
元のコードの'https://www.googleapis.com/auth/drive.metadata.readonly'
を変更しています。
詳細については、下記を確認してください。
https://developers.google.com/drive/v2/web/about-auth

成功すると、WEBのリンクが表示されるので、クリックすると認証ページになります。
承認後、コードが表示されるので、Colaboratory上のEnter verification code: と書かれた右側に入力してエンターキーを押すことで認証完了です。
次回は、作成したこのservice (Resource in module googleapiclient.discovery object)を使用して、クエリの実行や、ファイルのダウンロード、アップロードを行います。

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