【发布时间】:2020-03-31 09:44:27
【问题描述】:
我已遵循 Google 为使用 Python 提供的 quickstart,并且我已使用 Google 提供的适当范围从 Drive https://www.googleapis.com/auth/drive.readonly 下载文件,但我不断收到以下错误:
googleapiclient.errors.HttpError:https://www.googleapis.com/drive/v3/files/1RWpLGCWldcJyVqa0tIVlScg60ExEtcNIvJ7R9M8DuhM?alt=media 返回“只能下载具有二进制内容的文件。使用导出 使用 Google Docs 文件。”
当我尝试运行代码来下载文件时。
我可以读取驱动器上的文件,但我似乎无法从驱动器下载特定的电子表格,尽管我已尽了最大努力。下面是我的代码(经过编辑的文件路径和一些注释),用于通过 API 建立连接:
def gsuite_connect():
file_path = 'OMITTED/Loading'
# Get what permissions the user (using the API) will need. This as been set to high level
# access by default
scopes = ['https://www.googleapis.com/auth/drive.readonly']
# Access the tokens for G Suite to access the Drive. Ensure that if this file previous exists,
# that it is in the current working directory
store = file.Storage(os.path.join(file_path, 'storage.json'))
# Access the credentials for the Drive API
creds = store.get()
if not creds or creds.invalid:
print("\nUsing credentials found in client_id(secret).json")
flow = client.flow_from_clientsecrets(os.path.join(file_path, 'client_id.json'), scopes)
creds = tools.run_flow(flow, store)
http = creds.authorize(Http())
drive = discovery.build('drive', 'v3', http=http)
sheets = discovery.build('sheets', 'v4', http=http)
return drive, sheets
这是我用于根据Google provides 下载文件的功能(编辑的文件路径和一些评论):
def get_datalog(self):
dir_path = 'OMITTED/Downloads'
fname = "'FILENAME'"
files = self.drive.files().list(q="name = {}".format(fname),
fields="nextPageToken, files(id, name)").execute()
items = files.get('files', [])
# Error checking and subsequent downloading if file successfully found
if not items:
exit()
else:
# Change into the desired directory for storing the file and download file based on the
# retrieved ID
os.chdir(dir_path)
file_id = items[0]['id']
# Request download service
request = self.drive.files().get_media(fileId=file_id)
fh = io.FileIO(fname, mode='w')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download %d%%." % int(status.progress() * 100))
# Return the file path
return os.path.join(dir_path, fname)
我们将不胜感激!我不想显示敏感文件,例如 client_id.json 或任何其他凭据,但如果您需要更多信息,请告诉我!
【问题讨论】:
-
代码本身没有任何错误,应该可以正常工作,这让我知道您要下载什么类型的文件。我认为这与文件格式和大小有关,因此请指定此详细信息以便正确调试。
-
使用:developers.google.com/drive/api/v3/reference/files/get 查看文件的 MIME 类型。
-
非常感谢 Santhosh 的快速回复。这是一个谷歌表。我也无法访问其他文件,也无法从工作表中读取数据。我遇到了同样的错误,这让我认为可能还有其他事情在起作用。
-
我遇到了同样的错误。在我的情况下,原因是我的文件 ID 错误。我在谷歌驱动器中打开文件并从浏览器地址栏中的 url 获取 ID。这是错误的。所以我所做的是通过代码检索所有文件,使用 API,我注意到文件 ID 不同。所以当我使用从 API 返回的文件 id 时,我能够使用这个 id 来检索文件。我怀疑这对任何人都有帮助,但这是我的两分钱。
标签: python google-api google-drive-api