感谢Ido Ran 和brillb 的示例,我终于也解决了我的问题。上面给出的一些文档链接不再有效。为了增强上面的例子,我发现页面Google Photos APIs 最有用。它不仅记录了 API,还允许您以交互方式测试您的请求——如果没有这种测试能力,我可能永远不会让它工作。输入您的请求后,您可以在 cURL、HTTP 或 JAVASCRIPT 中看到您的编码示例 - 但对于 Python 则没有。
除了制作我的专辑列表之外,我还对
感兴趣
- 每张专辑的链接,
- 图片列表(在相册中或不在相册中),
- 链接到我的每个媒体项目以及找到它们的 URL
为了获得专辑的链接,您可以通过检索item['productUrl'] 来扩展上述示例。但是,很多时候该 URL 在 Firefox、IE 和 Edge 中对我不起作用(在非常简短地显示专辑后出现错误 404),但在 Chrome 和 Opera 中却可以(谁知道为什么)。
专辑封面照片的 URL 似乎更可靠:item['coverPhotoMediaItemId'],您可以在 Info 下找到专辑的链接。
除了使用albums 方法,您还可以访问sharedAlbums(并指定results.get('sharedAlbums', [])。我希望能够获得shareableUrl,但从未找到ShareInfo 资源作为结果。
对于图像列表,您可以选择两种方法:mediaItems.list 和 mediaItems.search。我不认为前者有用,因为它会返回一长串所有您的图像,而搜索允许按日期限制结果,照片拍摄 (未上传!)。还有一个get 和batchGet,我从未尝试过,因为您需要知道Google 照片为图像提供的项目ID。
每个方法都有一个限制 (pageSize) 用于返回的最大条目数。如果还有更多,它还会发送一个pageToken,您可以使用它来请求下一部分。
我终于想出了这个例子:
from os.path import join, dirname
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/photoslibrary.readonly'
store = file.Storage(join(dirname(__file__), 'token-for-google.json'))
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(join(dirname(__file__), 'client_id.json', SCOPES))
creds = tools.run_flow(flow, store)
google_photos = build('photoslibrary', 'v1', http=creds.authorize(Http()))
day, month, year = ('0', '6', '2019') # Day or month may be 0 => full month resp. year
date_filter = [{"day": day, "month": month, "year": year}] # No leading zeroes for day an month!
nextpagetoken = 'Dummy'
while nextpagetoken != '':
nextpagetoken = '' if nextpagetoken == 'Dummy' else nextpagetoken
results = google_photos.mediaItems().search(
body={"filters": {"dateFilter": {"dates": [{"day": day, "month": month, "year": year}]}},
"pageSize": 10, "pageToken": nextpagetoken}).execute()
# The default number of media items to return at a time is 25. The maximum pageSize is 100.
items = results.get('mediaItems', [])
nextpagetoken = results.get('nextPageToken', '')
for item in items:
print(f"{item['filename']} {item['mimeType']} '{item.get('description', '- -')}'"
f" {item['mediaMetadata']['creationTime']}\nURL: {item['productUrl']}")