2012-05-31 40 views
14

いくつかのLinuxサーバからGDrive(GDocs形式に変換可能なものだけでなく)にさまざまなファイルタイプをバックアップする必要があります。Pythonスクリプトを使用してGoogleドライブにファイルをアップロードするにはどうすればよいですか?

pythonスクリプトでこれを行うには、最も簡単で洗練された方法は何でしょうか? GDocsに関連するソリューションはどれも適用可能でしょうか?

https://developers.google.com/google-apps/documents-list/

ドキュメントリストAPIとドライブのAPIの両方が同じリソース(すなわち、同じ文書やファイル)との対話:

+3

gドライブにアップロードする2016の方法は何ですか? –

答えて

10

あなたはドライブに書き込み、スクリプトを記述するためにドキュメントリストAPIを使用することができます。 Pythonクライアントライブラリで

このサンプルでは、​​ドライブに変換されていないファイルをアップロードする方法を示しています。

http://code.google.com/p/gdata-python-client/source/browse/samples/docs/docs_v3_example.py#180

+4

ドキュメントリストAPIは2012年9月14日の時点で廃止され、GoogleドライブAPIはhttps://developers.google.com/drive/の代わりに使用する必要があります。 –

0

のpythonを使用してGoogleドライブにファイルを保存するため、現在のドキュメントはここで見つけることができます: https://developers.google.com/drive/v3/web/manage-uploads

しかし、googleドライブAPIがドキュメントの格納と検索を処理する方法は、POSIXファイルシステムと同じアーキテクチャに従いません。その結果、あなたのLinuxファイルシステム上でネストされたファイルの階層構造を保持したい場合、親ディレクトリがgoogleドライブに保存されるように多くのカスタムコードを書く必要があります。

さらに、Googleでは、通常のドライブアカウントへの書き込みアクセス権を得ることが困難です。あなたの許可範囲にはhttps://www.googleapis.com/auth/driveのリンクが含まれていなければなりません。ユーザーの通常アカウントにアクセスするためのトークンを取得するには、審査されていないアプリへのアクセスを提供するには、最初にjoin a groupを入力する必要があります。また、作成されるoauthトークンの保存期間は限られています。

ただし、アクセストークンを取得した場合、次のスクリプトを使用すると、ローカルマシンの任意のファイルをgoogleドライブの同じ(相対)パスに保存することができます。

def migrate(file_path, access_token, drive_space='drive'): 

    ''' 
     a method to save a posix file architecture to google drive 

    NOTE: to write to a google drive account using a non-approved app, 
      the oauth2 grantee account must also join this google group 
      https://groups.google.com/forum/#!forum/risky-access-by-unreviewed-apps 

    :param file_path: string with path to local file 
    :param access_token: string with oauth2 access token grant to write to google drive 
    :param drive_space: string with name of space to write to (drive, appDataFolder, photos) 
    :return: string with id of file on google drive 
    ''' 

# construct drive client 
    import httplib2 
    from googleapiclient import discovery 
    from oauth2client.client import AccessTokenCredentials 
    google_credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') 
    google_http = httplib2.Http() 
    google_http = google_credentials.authorize(google_http) 
    google_drive = discovery.build('drive', 'v3', http=google_http) 
    drive_client = google_drive.files() 

# prepare file body 
    from googleapiclient.http import MediaFileUpload 
    media_body = MediaFileUpload(filename=file_path, resumable=True) 

# determine file modified time 
    import os 
    from datetime import datetime 
    modified_epoch = os.path.getmtime(file_path) 
    modified_time = datetime.utcfromtimestamp(modified_epoch).isoformat() 

# determine path segments 
    path_segments = file_path.split(os.sep) 

# construct upload kwargs 
    create_kwargs = { 
     'body': { 
      'name': path_segments.pop(), 
      'modifiedTime': modified_time 
     }, 
     'media_body': media_body, 
     'fields': 'id' 
    } 

# walk through parent directories 
    parent_id = '' 
    if path_segments: 

    # construct query and creation arguments 
     walk_folders = True 
     folder_kwargs = { 
      'body': { 
       'name': '', 
       'mimeType' : 'application/vnd.google-apps.folder' 
      }, 
      'fields': 'id' 
     } 
     query_kwargs = { 
      'spaces': drive_space, 
      'fields': 'files(id, parents)' 
     } 
     while path_segments: 
      folder_name = path_segments.pop(0) 
      folder_kwargs['body']['name'] = folder_name 

    # search for folder id in existing hierarchy 
      if walk_folders: 
       walk_query = "name = '%s'" % folder_name 
       if parent_id: 
        walk_query += "and '%s' in parents" % parent_id 
       query_kwargs['q'] = walk_query 
       response = drive_client.list(**query_kwargs).execute() 
       file_list = response.get('files', []) 
      else: 
       file_list = [] 
      if file_list: 
       parent_id = file_list[0].get('id') 

    # or create folder 
    # https://developers.google.com/drive/v3/web/folder 
      else: 
       if not parent_id: 
        if drive_space == 'appDataFolder': 
         folder_kwargs['body']['parents'] = [ drive_space ] 
        else: 
         del folder_kwargs['body']['parents'] 
       else: 
        folder_kwargs['body']['parents'] = [parent_id] 
       response = drive_client.create(**folder_kwargs).execute() 
       parent_id = response.get('id') 
       walk_folders = False 

# add parent id to file creation kwargs 
    if parent_id: 
     create_kwargs['body']['parents'] = [parent_id] 
    elif drive_space == 'appDataFolder': 
     create_kwargs['body']['parents'] = [drive_space] 

# send create request 
    file = drive_client.create(**create_kwargs).execute() 
    file_id = file.get('id') 

    return file_id 

PS。私はこのスクリプトをlabpackのpythonモジュールから修正しました。 rcj1492によって書かれたこのモジュールには、POSIXファイルシステムを保存する方法でgoogleドライブのファイルの保存、ロード、検索、および削除を処理するクラスdriveClientがあります。

from labpack.storage.google.drive import driveClient 
0

私はPyDriveはエレガントドライブのAPIを扱うことが判明し、それはまた、(特に認証部を介してユーザーを歩く)documentation偉大持っています。

EDIT:Automating pydrive verification processPydrive google drive automate authentication上の材料であることを組み合わせて、それは物事が軌道に乗るためにいくつかの素晴らしいドキュメントになります。それは、どこから始めるのか混乱している人を助けてくれることを願っています。

関連する問題