【问题标题】:Access Google Photo API with Python using google-api-python-client使用 google-api-python-client 使用 Python 访问 Google Photo API
【发布时间】:2018-05-28 20:39:40
【问题描述】:

根据Google API Client Libraries 页面,可以使用 python 客户端库访问 Google Photos API,但在使用 pip install -t lib/ google-api-python-client 安装后,我看不到任何与 Photos API 相关的内容。

如何使用 Google 构建的客户端库而不是手动调用 REST API?

【问题讨论】:

标签: python google-app-engine google-photos-api


【解决方案1】:

感谢Ido Ranbrillb 的示例,我终于也解决了我的问题。上面给出的一些文档链接不再有效。为了增强上面的例子,我发现页面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.listmediaItems.search。我不认为前者有用,因为它会返回一长串所有您的图像,而搜索允许按日期限制结果,照片拍摄 (未上传!)。还有一个getbatchGet,我从未尝试过,因为您需要知道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']}")

【讨论】:

  • 请阅读本文以避免浪费大量时间。 Google Photos API 只允许您控制从您的应用程序创建的数据,而不是预先存在的数据。因此,如果您想移动现有图片,请更新它们的描述或将它们添加到相册中......你不能。您不能以任何方式接触预先存在的数据。阅读这个 -> *.com/a/56897605/3443057
  • 这确实节省了很多时间!
【解决方案2】:

我没有找到任何示例,因此我采用 Drive API v3 示例并将其改编为 Photos v1 API。

You can see and use the example.

要点是:

from apiclient.discovery import build

service = build('photoslibrary', 'v1', http=creds.authorize(Http()))
results = service.albums().list(
    pageSize=10, fields="nextPageToken,albums(id,title)").execute()

【讨论】:

  • 谢谢!会喜欢它,如果有人可以发布有关如何更新照片的示例(补丁/发布休息电话),例如更新照片的描述或日期
【解决方案3】:

该 API 的功能比上面示例中显示的稍差,它不支持“字段”。但它确实有效:

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('token-for-google.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
    creds = tools.run_flow(flow, store)
gdriveservice = build('photoslibrary', 'v1', http=creds.authorize(Http()))

results = gdriveservice.albums().list(
    pageSize=10).execute()
items = results.get('albums', [])
for item in items:
        print(u'{0} ({1})'.format(item['title'].encode('utf8'), item['id']))

【讨论】:

    【解决方案4】:

    查看 API 的文档here

    更具体地说是here。不过似乎很有限。

    【讨论】:

    • 我都找到了,但是安装库后我没有看到要导入的 api
    • 你试过import googleapiclient.photoslibrary吗?
    • @ArdentLearner:那个导入给了我“ImportError: No module named photoslibrary”。