Google Drive API(python) - 无法检索照片

时间:2017-12-09 13:58:44

标签: python google-drive-api

我正在尝试编写一个python脚本,它将从我的Google云端硬盘中检索所有照片。我创建了一个服务帐户,我可以检索样本pdf文件"入门"这是在我的Google云端硬盘帐户中。但是我无法使用脚本检索* .jpg。

在这里使用测试api并选择phots,作为空间参数驱动我获得预期结果,https://developers.google.com/drive/v3/reference/files/list

以下是我要执行的代码:

scopes =['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.photos.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name(<service account file name>, scopes=scopes)
http_auth = credentials.authorize(Http())
drive_service = build('drive','v3', http=http_auth)

page_token = None
while True:
    response = drive_service.files().list(spaces='drive,photos',
                                      fields='nextPageToken, files(id, name)',
                                      pageToken=page_token).execute()
    for file in response.get('files', []):
        # Process change
        print 'Found file: %s (%s)' % (file.get('name'), file.get('id'))
    page_token = response.get('nextPageToken', None)
    if page_token is None:
        print "No more photos"
        break;

这是我期望获得的,这是我使用api测试链接时得到的结果:

{
"kind": "drive#fileList",
"incompleteSearch": false,
"files": [
{
"kind": "drive#file",
"id": "0B0UYmRxQ5YMsc3RhcnRlcl9maWxl",
"name": "Getting started",
"mimeType": "application/pdf"
},
{
"kind": "drive#file",
"id": "1-b7wksGUCb825wNx7Ov-Si6EWaN6zSx11w",
"name": "IMG_180936.jpg",
"mimeType": "image/jpeg"
}
]
}

但这是我执行代码时得到的结果:

Found file: Getting started (0B7zoeZ330KvQc3RhcnRlcl9maWxl)
No more photos

不会产生任何错误。

2 个答案:

答案 0 :(得分:0)

我认为您需要在此documentation中的代码中指定q="mimeType='image/jpeg'

page_token = None
while True:
    response = drive_service.files().list(q="mimeType='image/jpeg'",
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=page_token).execute()
    for file in response.get('files', []):
        # Process change
        print 'Found file: %s (%s)' % (file.get('name'), file.get('id'))
    page_token = response.get('nextPageToken', None)
    if page_token is None:
        break;

答案 1 :(得分:0)

感谢您的回复。在进一步调查该问题之后,我发现问题在于使用ServiceAccount并且无法访问添加到Google Photo的照片。如果我与ServiceAccount共享照片,我可以成功检索信息。

API Explorer使用OAuth2,可以访问个人帐户中的所有内容。