簡體   English   中英

如何使用 Python 和 Drive API v3 從 Google Drive 下載文件

[英]How to download a file from Google Drive using Python and the Drive API v3

我曾嘗試使用 python 腳本將文件從 Google Drive 下載到我的本地系統,但在運行 Python 腳本時面臨“禁止”問題。 腳本如下:

import requests

url = "https://www.googleapis.com/drive/v3/files/1wPxpQwvEEOu9whmVVJA9PzGPM2XvZvhj?alt=media&export=download"

querystring = {"alt":"media","export":"download"}

headers = {
    'Authorization': "Bearer TOKEN",

    'Host': "www.googleapis.com",
    'Accept-Encoding': "gzip, deflate",
    'Connection': "keep-alive",
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.url)
#
import wget
import os
from os.path import expanduser


myhome = expanduser("/home/sunarcgautam/Music")
### set working dir
os.chdir(myhome)

url = "https://www.googleapis.com/drive/v3/files/1wPxpQwvEEOu9whmVVJA9PzGPM2XvZvhj?alt=media&export=download"
print('downloading ...')
wget.download(response.url)

在這個腳本中,我遇到了禁止問題。 我在腳本中做錯了什么嗎?

我還嘗試了在 Google Developer 頁面上找到的另一個腳本,如下所示:

import auth
import httplib2
SCOPES = "https://www.googleapis.com/auth/drive.scripts"
CLIENT_SECRET_FILE = "client_secret.json"
APPLICATION_NAME = "test_Download"
authInst = auth.auth(SCOPES, CLIENT_SECRET_FILE, APPLICATION_NAME)
credentials = authInst.getCredentials()
http = credentials.authorize(httplib2.Http())
drive_serivce = discovery.build('drive', 'v3', http=http)

file_id = '1Af6vN0uXj8_qgqac6f23QSAiKYCTu9cA'
request = drive_serivce.files().export_media(fileId=file_id,
                                             mimeType='application/pdf')
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))

這個腳本給了我一個URL mismatch error

那么應該為 Google 控制台憑據中的重定向 URL 提供什么? 或該問題的任何其他解決方案? 我是否必須在這兩個腳本中從 Google 授權我的 Google 控制台應用程序? 如果是這樣,授權應用程序的過程將是什么,因為我還沒有找到任何關於它的文件。

要向 Google API 發出請求,工作流程本質上如下:

  1. 轉到開發人員控制台,如果還沒有,請登錄。
  2. 創建一個雲平台項目。
  3. 為您的項目啟用您有興趣與項目應用程序一起使用的 API(例如:Google Drive API)。
  4. 創建並下載OAuth 2.0 客戶端 ID憑據,這將使您的應用獲得使用已啟用 API 的授權。
  5. 轉到OAuth 同意屏幕,單擊在此處輸入圖片說明 並使用添加您的范圍在此處輸入圖片說明 按鈕。 (范圍: https : //www.googleapis.com/auth/drive.readonly適合您)。 根據您的需要選擇內部/外部,現在忽略警告(如果有)。
  6. 為了獲取用於發出 API 請求的有效令牌,應用程序將通過 OAuth 流程來接收授權令牌。 (因為它需要同意)
  7. 在 OAuth 流程中,用戶將被重定向到您的 OAuth 同意屏幕,在該屏幕上將要求用戶批准或拒絕對您應用的請求范圍的訪問。
  8. 如果獲得同意,您的應用將收到授權令牌。
  9. 將請求中的令牌傳遞給您的授權 API 端點。 [ 2 ]
  10. 構建驅動服務以發出 API 請求(您將需要有效的令牌) [ 1 ]

筆記:

Drive API v3 的 Files 資源的可用方法在這里

使用 Python Google APIs Client 時,您可以根據 Google APIs Client for Python 文檔使用export_media()get_media()


重要的:

此外,請檢查您使用的范圍,實際上允許您做您想做的事情(從用戶的驅動器下載文件)並相應地設置它。 ATM 您的目標范圍不正確。 請參閱OAuth 2.0 API 范圍


示例代碼參考:

  1. 構建驅動服務:
import google_auth_oauthlib.flow
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
 
 
class Auth:
 
    def __init__(self, client_secret_filename, scopes):
        self.client_secret = client_secret_filename
        self.scopes = scopes
        self.flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(self.client_secret, self.scopes)
        self.flow.redirect_uri = 'http://localhost:8080/'
        self.creds = None
 
    def get_credentials(self):
        flow = InstalledAppFlow.from_client_secrets_file(self.client_secret, self.scopes)
        self.creds = flow.run_local_server(port=8080)
        return self.creds

 
# The scope you app will use. 
# (NEEDS to be among the enabled in your OAuth consent screen)
SCOPES = "https://www.googleapis.com/auth/drive.readonly"
CLIENT_SECRET_FILE = "credentials.json"
 
credentials = Auth(client_secret_filename=CLIENT_SECRET_FILE, scopes=SCOPES).get_credentials()
 
drive_service = build('drive', 'v3', credentials=credentials)
  1. 發出導出或獲取文件的請求
request = drive_service.files().export(fileId=file_id, mimeType='application/pdf')

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))

# The file has been downloaded into RAM, now save it in a file
fh.seek(0)
with open('your_filename.pdf', 'wb') as f:
    shutil.copyfileobj(fh, f, length=131072)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM