【问题标题】:How to download a file from Google Drive using Python and the Drive API v3如何使用 Python 和 Drive API v3 从 Google Drive 下载文件
【发布时间】:2020-05-23 11:12:29
【问题描述】:

我曾尝试使用 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))

这个脚本给了我一个网址不匹配错误

那么在 Google 控制台凭据中应该为重定向 URL 提供什么?或任何其他解决方案?我是否必须在两个脚本中从 Google 授权我的 Google 控制台应用程序?如果是这样,授权该应用程序的过程将是什么,因为我还没有找到任何相关文件。

【问题讨论】:

标签: python google-drive-api


【解决方案1】:

要向 Google API 发出请求,工作流程实质上如下:

  1. 转到developer console,如果你还没有登录。
  2. 创建一个云平台项目。
  3. 为您的项目启用您有兴趣在项目应用中使用的 API(例如:Google Drive API)。
  4. 创建并下载 OAuth 2.0 客户端 ID 凭据,以便您的应用获得使用已启用 API 的授权。
  5. 前往OAuth consent screen,单击,然后使用 按钮添加您的范围。 (范围:https://www.googleapis.com/auth/drive.readonly 适合您)。根据您的需要选择内部/外部,现在忽略警告(如果有)。
  6. 为了获得发出 API 请求的有效令牌,应用程序将通过 OAuth 流程来接收授权令牌。 (因为需要同意)
  7. 在 OAuth 流程期间,用户将被重定向到您的 OAuth 同意屏幕,在该屏幕上将要求用户批准或拒绝访问您的应用请求的范围。
  8. 如果获得同意,您的应用将收到一个授权令牌。
  9. 将请求中的令牌传递给您的授权 API 端点。[2]
  10. 构建驱动服务以发出 API 请求(您将需要有效的令牌)[1]

注意:

Drive API v3 文件资源的可用方法是here

使用 Python Google APIs 客户端时,您可以使用 export_media()get_media() 作为 per Google APIs Client for Python documentation


重要提示:

另外,请检查您使用的范围,实际上是否允许您做您想做的事情(从用户的驱动器下载文件)并进行相应的设置。 ATM 你的目标范围不正确。见OAuth 2.0 API Scopes


示例代码参考:

  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)

【讨论】:

  • 我从哪里得到那个文件?它是否在我的脚本所在的同一个文件夹中?如果是这样,我无法查看该文件。
  • 是的,该文件将存储在您的 python 脚本运行的位置。
  • 但我无法打开该文件。打开文件时出现致命错误。
  • 我有 .png 扩展名。
猜你喜欢
  • 2023-02-06
  • 2021-10-05
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多