2016-12-21 5 views
0

Googleドライブで特定のファイルの直接ダウンロードリンクを取得したいと思いますが、Google APIクライアントのPythonを使用しています。これは基本的にquickstart exampleのコピーである:Python APIを使用してGoogleドライブのファイルのdownloadUrlプロパティを取得できません

SCOPES = "https://www.googleapis.com/auth/drive" 
FILE_ID = "xxxxxx" 


def get_credentials(): 
    ... 
    return credentials 

if __name__ == '__main__': 
    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http()) 
    service = discovery.build("drive", "v3", http=http) 

    web_link = service.files().get(fileId=FILE_ID, fields="webContentLink").execute() # success 
    download_link = service.files().get(fileId=FILE_ID, fields="downloadUrl").execute() # throw an error 

それから私は400エラーを得た:

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/drive/v3/files/xxxxxx?alt=json&fields=downloadUrl returned "Invalid field selection downloadUrl"> 

私が検索し、この問題についてのすべての関連の質問をお読みください。一つとしてthis questionで述べている:

The difference between this downloadURL and the webContentLink is that the webContentLink uses authorization from the user's browser cookie, the downloadURL requires an authorized API request (using OAuth 2.0).

だから私は多分私が正常に要求を承認していないと思いました。しかし、主要部分の最初の3つのステートメントは、guideに応じて私のためにそれをやった:

Use the authorize() function of the Credentials class to apply necessary credential headers to all requests made by an httplib2.Http instance ... Once an httplib2.Http object has been authorized, it is typically passed to the build function

をだから何が私のプログラムが悪いですの? urllibを使って自分のリクエストを書いたり、エラーを再現するようにリクエストしたいのであれば、どうしたらいいですか?

答えて

1

downloadURLは、GoogleドライブのAPIには、使用しているように見えるバージョン2なくバージョン3ファイルのリソースのために利用可能であるフィールドです。

GoogleドライブAPI v3では、files.get?alt=mediaと指定してファイルをダウンロードし、特定のURLを見つけることなく直接ファイルをダウンロードするようにフィールドが置き換えられました。ここでYou can read more about the differences and changes between API v2 and v3 here.

は、GoogleドライブのAPI v3のとのpythonのGoogle APIクライアントライブラリを使用してファイルをダウンロードする方法の例です:

file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M' 
request = drive_service.files().get_media(fileId=file_id) 
fh = io.BytesIO() 
downloader = MediaIoBaseDownload(fh, request) 
done = False 
while done is False: 
    status, done = downloader.next_chunk() 
    print "Download %d%%." % int(status.progress() * 100) 

Check out the official documentation regarding downloading files using the API v3 here for more examples.

+0

ああ、実際には、私が直接ダウンロードを共有したいですそれをダウンロードするのではなく他の人にリンクしてください。私はより便利だと思うので、私はwebContentLinkへの直接ダウンロードリンクを好む(人々は自分の共有リンクをクリックするだけで自分のファイルを直接ダウンロードできる)。私はv3でそれをすることはできません、そうですか?何か手がかりがある場合は、教えてください。それでも、ありがとう。 – Spike

+0

@Spikeファイルが公に共有されている場合、 'webContentLink'はログインまたは認証を必要とせずにダウンロードするためのURLです。あるいは、サポートするファイルタイプでGoogleドライブビューアを使ってファイルを開くための 'webViewLink'があります。 'webContentLink'はファイルがウェブ上で公に共有されている場合にのみ認証を必要としないことに注意してください。ファイルが公に共有されていない場合は、そのファイルへのアクセス権が与えられているユーザーがログインする必要があります。 – danielx