使用 google-api-python-client 使用 Python 访问 Google 照片 API
Access Google Photo API with Python using google-api-python-client
根据 Google API Client Libraries 页面,可以使用 python 客户端库访问 Google 照片 API,但在使用 pip install -t lib/ google-api-python-client
安装后我没有看到任何与照片相关的内容 API。
如何使用 Google 构建的客户端库而不是手动调用 REST APIs?
查看 API 的文档 here。
更具体地说 here。不过似乎很有限。
我没有找到任何示例,所以我采用了 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()
API 比上面示例中显示的功能稍差,它不支持 "fields"。但它确实有效:
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']))
感谢Ido Ran's and 's examples, I finally got my problem solved too. Some of the documentation links given above are not valid any more. Trying to enhance above examples, I found the page Google Photos APIs最有用。它不仅记录了 API,而且还允许您以交互方式测试您的请求 - 如果没有该测试功能,我可能从来没有让它工作过。输入您的请求后,您可以在 cURL、HTTP 或 JAVASCRIPT 中看到您的编码示例 - 但在 Python 中没有任何内容。
除了制作我的专辑列表,我还对
感兴趣
- link到每张专辑,
- 图像列表(是否在相册中),
- link 我的每个媒体项目和 URL 找到它们
为了得到 link 到相册,您可以简单地通过检索 item['productUrl']
来扩展上面的例子。然而,很多时候 URL 在 Firefox、IE 或 Edge 中对我不起作用(非常简短地显示相册后出现错误 404),但在 Chrome 和 Opera 中却起作用(谁知道为什么)。
相册封面照片的 URL 似乎更可靠:item['coverPhotoMediaItemId']
并且您会在 [=41] 下找到相册的 link =]信息.
除了使用albums
方法,您还可以访问sharedAlbums
(并指定results.get('sharedAlbums', [])
。我希望能够获得shareableUrl
,但是从未在结果中找到 ShareInfo
资源。
对于图像列表,您可以选择两种方法:mediaItems.list
和mediaItems.search
。我不认为前者有用,因为它 returns 一长串 所有 你的图片,而搜索允许限制结果日期,照片已拍摄(未上传!)。还有一个 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']}")
根据 Google API Client Libraries 页面,可以使用 python 客户端库访问 Google 照片 API,但在使用 pip install -t lib/ google-api-python-client
安装后我没有看到任何与照片相关的内容 API。
如何使用 Google 构建的客户端库而不是手动调用 REST APIs?
查看 API 的文档 here。
更具体地说 here。不过似乎很有限。
我没有找到任何示例,所以我采用了 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()
API 比上面示例中显示的功能稍差,它不支持 "fields"。但它确实有效:
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']))
感谢Ido Ran's and
除了制作我的专辑列表,我还对
感兴趣- link到每张专辑,
- 图像列表(是否在相册中),
- link 我的每个媒体项目和 URL 找到它们
为了得到 link 到相册,您可以简单地通过检索 item['productUrl']
来扩展上面的例子。然而,很多时候 URL 在 Firefox、IE 或 Edge 中对我不起作用(非常简短地显示相册后出现错误 404),但在 Chrome 和 Opera 中却起作用(谁知道为什么)。
相册封面照片的 URL 似乎更可靠:item['coverPhotoMediaItemId']
并且您会在 [=41] 下找到相册的 link =]信息.
除了使用albums
方法,您还可以访问sharedAlbums
(并指定results.get('sharedAlbums', [])
。我希望能够获得shareableUrl
,但是从未在结果中找到 ShareInfo
资源。
对于图像列表,您可以选择两种方法:mediaItems.list
和mediaItems.search
。我不认为前者有用,因为它 returns 一长串 所有 你的图片,而搜索允许限制结果日期,照片已拍摄(未上传!)。还有一个 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']}")