使用google-api-python-client使用Python访问Google Photo API

Ido*_*Ran 7 python google-app-engine google-photos-api

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

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

Wil*_*ied 8

感谢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。我不认为前者有用,因为它返回所有图像的长列表,而搜索允许按日期限制结果,照片是拍摄的(未上传!)。还有一个getand 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']}")
Run Code Online (Sandbox Code Playgroud)

  • **请阅读本文以避免浪费大量时间**。Google Photos API 只允许您控制从应用程序创建的数据,而不是预先存在的数据。因此,如果您想移动现有的图片,请更新它们的描述或将它们添加到相册中.. **你不能**。您无法以任何方式触及预先存在的数据。阅读此内容 -> /sf/answers/3982832381/ (10认同)
  • 我不确定@SanJay 到底指的是什么。但这是 2022 年 4 月 13 日,通过 photoslibrary API,我能够列出相册或列出照片内容。但是,我需要将 `static_discovery=False` 添加到构建方法[源](/sf/ask/4668295901/) (3认同)

Ido*_*Ran 5

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

您可以看到并使用该示例

要点是:

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()
Run Code Online (Sandbox Code Playgroud)


小智 5

该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']))
Run Code Online (Sandbox Code Playgroud)