首页 > 解决方案 > Python:使用`export_media`(Google Drive API)下载PDF时传递`gridlines = false`

问题描述

我已按照 Drive API v3 文档下载 Google 文档。根据示例,我能够成功下载 PDF 格式的电子表格,构建请求如下:

from googleapiclient.discovery import build

drive_service = build('drive', 'v3', credentials=creds)

SPREADSHEET_ID = 'mySpreadSheetID'
request = drive_service.files().export_media(fileId=SPREADSHEET_ID,
                                             mimeType='application/pdf',
                                             )

我希望将此答案中的自定义参数作为请求的一部分传递,特别是 set gridlines=false

我从文档中googleapiclient.http.HttpRequest发现我可以通过以下方式进一步检查请求:

request.to_json()

这给了我:

('{"uri": '
 '"https://www.googleapis.com/drive/v3/files/mySpreadSheetID/export?mimeType=application%2Fpdf&alt=media", '
 '"method": "GET", "body": null, "headers": {"accept": "*/*", '
 '"accept-encoding": "gzip, deflate", "user-agent": "(gzip)", '
 '"x-goog-api-client": "gdcl/1.7.11 gl-python/3.7.4"}, "methodId": '
 '"drive.files.export", "resumable": null, "response_callbacks": [], '
 '"_in_error_state": false, "body_size": 0, "resumable_uri": null, '
 '"resumable_progress": 0}')```

我怀疑&gridlines=false需要uri在发出请求之前附加到,但是我不确定如何修改它。

我是否走在正确的轨道上,如果没有,是否有另一种方法可以从 Python 库中传递这些参数?

标签: pythongoogle-drive-api

解决方案


  • 您想将 Google 电子表格导出为 PDF 文件。
  • 您想使用 的查询参数gridlines=false
  • 您想使用 python 来实现这一点。
  • 您的访问令牌可用于导出 Google 电子表格。

如果我的理解是正确的,这个答案怎么样?请认为这只是几个可能的答案之一。

修改点:

  • 在本次修改中,gridlines=false通过直接修改requests.

修改后的脚本:

SPREADSHEET_ID = "###"  # Please set the Spreadsheet ID.

drive_service = build('drive', 'v3', credentials=creds)
request = drive_service.files().export_media(fileId=SPREADSHEET_ID, mimeType='application/pdf')

# Here, the endpoint is modified.
request.uri = "https://docs.google.com/spreadsheets/d/" + SPREADSHEET_ID + "/export?format=pdf&gridlines=false"

fh = io.FileIO('sample.pdf', mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print('Download %d%%.' % int(status.progress() * 100))
  • 在这种情况下,您也可以使用request = drive_service.files().export_media(fileId="", mimeType=""). 因为端点被修改了。

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。


推荐阅读