LoginSignup
3
3

More than 5 years have passed since last update.

Google API Client Library for Pythonでドライブのデータを転送する

Last updated at Posted at 2017-11-27

概要

・外部のサーバからサービスアカウントで認証して、ドライブデータを転送する。
google-api-python-clientでGoogleAPIのAdminsdkを使う。

認証手順

Google Developer Console

1,プロジェクト作成
2,サービスアカウントを作成

Gsuite管理コンソール

1,作成したサービスアカウントのIDに対してAPIアクセスを承認する

実行コード

DjangoのTemplateContext使用

datatransfer.py
import httplib2
import json
from googleapiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
from django.template import Context, Template

class Credentials():
    def delegated_credentials(self):
        client_secret = '/home/user/project/src/resource/json/client_secret.json' #任意のパス
        scopes = 'scopes'
        delegated_mail_address = 'admin@test.com'

        #認証
        credentials = ServiceAccountCredentials.from_json_keyfile_dict(
            client_secret, scopes=scopes)
        delegated_credentials = credentials.create_delegated(delegated_mail_address)

        return delegated_credentials

    def data_transfer_service(self, delegated_credentials):

        http_auth = delegated_credentials.authorize(httplib2.Http())
        service = discovery.build(
            'admin', 'datatransfer_v1', http=http_auth, cache_discovery=False)
        return service

class DataTransfer():
    def transfer_insert(self, service):
        appid = '55656082996' #ドライブのID
        newown_id = '123456789012' # 転送先のID
        user_id =  '111122223333'
        api_template = '/home/user/project/src/resource/json/TransferInsert.json' #任意のパス

        #テンプレート読み込み
        with open(api_template, 'r') as f:
            text = f.read()
        apitemplate = Template(text)
        d = Context({'appid': appid, 'newown': newown_id, 'oldown': user_id})
        body = json.loads(apitemplate.render(d))

        #データ転送
        service.transfers().insert(body=body).execute()


credentials = Credentials()
datatranfer = DataTransfer()

delegated_credentials = credentials.delegated_credentials()
service = credentials.data_transfer_service(delegated_credentials)

datatranfer.transfer_insert(service)

サービスアカウントのキーファイル

client_secret.json
{
  "type": "service_account",
  "project_id": "test-project-01",
  "private_key_id": "private_key_id",
  "private_key": "-----BEGIN PRIVATE KEY-----xxxxxxxxxxxxx-----END PRIVATE KEY-----\n",
  "client_email": "accountname@test-project-01.iam.gserviceaccount.com",
  "client_id": "client_id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/accountname@test-project-01.iam.gserviceaccount.com"
}

APIリクエスト用のテンプレート

DataTransferInsert.json
{
  "kind": "admin#datatransfer#DataTransfer",
  "applicationDataTransfers": [
    {
      "applicationTransferParams": [
        {
          "key": "PRIVACY_LEVEL",
          "value": ["SHARED","PRIVATE"]
        }
      ],
      "applicationId": "{{appid}}"
    }
  ],
  "newOwnerUserId": "{{newown}}",
  "oldOwnerUserId": "{{oldown}}"
}
3
3
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
3