Python Google照片API列出相册中的项目



我在扩展列出相册id所需的API调用时遇到问题,以便能够列出相册中包含的项目。下面显示了我为检索相册ID所做的一个示例。除了这个例子之外,我还尝试扩展这个脚本,以便能够列出特定相册中包含的项目。

from httplib2 import Http
from oauth2client import file, client, tools
from apiclient.discovery import build
SCOPES = 'https://www.googleapis.com/auth/photoslibrary.readonly'
store = file.storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('photoslibrary', 'v1', http=creds.authorize(Http()))
hasNextPageToken = False
nextPageToken = ""
results = service.albums().list(pageSize=10).execute()
if 'nextPageToken' in results:
hasNextPageToken = True
nextPageToken = results['nextPageToken']
for album in results['albums']:
albumId = album['id']
print(albumId)

现在,对于我试图从上面的例子中修改的代码,以便能够列出由albumId:定义的给定相册中的项目

from httplib2 import Http
from oauth2client import file, client, tools
from apiclient.discovery import build
SCOPES = 'https://www.googleapis.com/auth/photoslibrary.readonly'
store = file.storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('photoslibrary', 'v1', http=creds.authorize(Http()))
hasNextPageToken = False
nextPageToken = ""
albumId = [albumIdFromPreviousStep]
results = service.mediaItems().search(pageSize=10,albumId=albumId).execute()

当我尝试打印results时,我收到一个关于接收意外关键字参数albumId的错误。

api调用的搜索格式不同,它是https://photoslibrary.googleapis.com/v1/mediaItems:search

错误是否源于使Python中的变量无效的:mediaItems:search?或者这与搜索调用是POST而不是GET这一事实有关?或者,其他什么?

mediaitems:search需要一个JSON结构的参数体,以便将返回的项目限制为特定的albumId。

修改原始帖子中代码的第二部分可以得到所需的结果。

from httplib2 import Http
from oauth2client import file, client, tools
from apiclient.discovery import build
SCOPES = 'https://www.googleapis.com/auth/photoslibrary.readonly'
store = file.storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('photoslibrary', 'v1', http=creds.authorize(Http()))
hasNextPageToken = False
nextPageToken = ""
body = {
"albumId": [AlbumId],
"pageSize": 10
}
results = service.mediaItems().search(body=body).execute()
print(results)

现在,收集所有其他项目的数据需要合并nextPageToken并在结果中循环。

我看不到您在修改后的代码中定义的albumId

results = service.mediaItems().search(pageSize=10,**albumId=albumId**).execute()

你复制的代码清楚地定义了

for album in results['albums']:
albumId = album['id']
print(albumId)

最新更新