【问题标题】:Google Photos API + python: Working non-deprecated exampleGoogle Photos API + python:工作的非弃用示例
【发布时间】:2019-12-05 17:12:34
【问题描述】:

我一直在寻找这样的混合代码示例。但是没有维护的库(google-auth)+完整的工作示例。不再支持google-api-python-clientoauth2client (https://github.com/googleapis/google-api-python-client/issues/651)。

这是一个使用已弃用库的工作示例,但我希望看到一些允许完全访问 api (searching by albumId currently doesn't work with this library) 的示例:

from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

# Setup the Photo v1 API
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()))

# Call the Photo v1 API
results = service.albums().list(
    pageSize=10, fields="nextPageToken,albums(id,title)").execute()
items = results.get('albums', [])
if not items:
    print('No albums found.')
else:
    print('Albums:')
    for item in items:
        print('{0} ({1})'.format(item['title'].encode('utf8'), item['id']))

【问题讨论】:

    标签: python google-photos-api google-auth-library


    【解决方案1】:
    • 您想使用google_auth 而不是oauth2client,因为oauth2client 已被弃用。
    • 您已经能够使用 Photo API。

    如果我的理解是正确的,那么这个答案呢?请认为这只是几个可能的答案之一。

    例如,授权示例脚本可以在the Quickstart of Drive API with python 看到。您可以看到安装库的方法。使用它,您的脚本可以修改如下。

    修改后的脚本:

    from __future__ import print_function
    import pickle
    import os.path
    from googleapiclient.discovery import build
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    
    
    def main():
        credentialsFile = 'credentials.json'  # Please set the filename of credentials.json
        pickleFile = 'token.pickle'  # Please set the filename of pickle file.
    
        SCOPES = ['https://www.googleapis.com/auth/photoslibrary']
        creds = None
        if os.path.exists(pickleFile):
            with open(pickleFile, 'rb') as token:
                creds = pickle.load(token)
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    credentialsFile, SCOPES)
                creds = flow.run_local_server()
            with open(pickleFile, 'wb') as token:
                pickle.dump(creds, token)
    
        service = build('photoslibrary', 'v1', credentials=creds)
    
        # Call the Photo v1 API
        results = service.albums().list(
            pageSize=10, fields="nextPageToken,albums(id,title)").execute()
        items = results.get('albums', [])
        if not items:
            print('No albums found.')
        else:
            print('Albums:')
            for item in items:
                print('{0} ({1})'.format(item['title'].encode('utf8'), item['id']))
    
    
    if __name__ == '__main__':
        main()
    
    • 关于检索专辑列表的脚本,使用了您的脚本。
    • 当您运行此脚本时,首先会运行授权过程。所以请授权范围。此过程只需要运行一次。但是如果要更改范围,请删除pickle文件并重新授权。

    参考资料:

    如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

    新增1:

    如果你想使用the method of mediaItems.search,下面的示例脚本怎么样?关于授权脚本,请使用上面的脚本。

    示例脚本:

    service = build('photoslibrary', 'v1', credentials=creds)
    albumId = '###'  # Please set the album ID.
    results = service.mediaItems().search(body={'albumId': albumId}).execute()
    print(results)
    

    新增2:

    • 您想从我建议的上述示例脚本中删除 googleapiclient
    • 您想使用google_auth_oauthlib.flowgoogle.auth.transport.requests 检索访问令牌。
    • 您想使用python的request而不使用googleapiclient来检索特定专辑中的媒体项目列表。

    如果我的理解是正确的,这个示例脚本怎么样?

    示例脚本:

    在使用此脚本之前,请先设置albumId的变量。

    from __future__ import print_function
    import json
    import pickle
    import os.path
    import requests
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    
    
    def main():
        credentialsFile = 'credentials.json'
        pickleFile = 'token.pickle'
    
        SCOPES = ['https://www.googleapis.com/auth/photoslibrary.readonly']
        creds = None
        if os.path.exists(pickleFile):
            with open(pickleFile, 'rb') as token:
                creds = pickle.load(token)
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    credentialsFile, SCOPES)
                creds = flow.run_local_server()
            with open(pickleFile, 'wb') as token:
                pickle.dump(creds, token)
    
        albumId = '###'  # <--- Please set the album ID.
    
        url = 'https://photoslibrary.googleapis.com/v1/mediaItems:search'
        payload = {'albumId': albumId}
        headers = {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + creds.token
        }
        res = requests.post(url, data=json.dumps(payload), headers=headers)
        print(res.text)
    
    
    if __name__ == '__main__':
        main()
    

    注意:

    • 在这种情况下,您可以同时使用https://www.googleapis.com/auth/photoslibrary.readonlyhttps://www.googleapis.com/auth/photoslibrary 的范围。

    参考:

    【讨论】:

    • 我不确定,但我认为 InstalledAppFlow 与 Google Photos API 提到的 doesn't support 的“服务帐户”相同,所以当我使用我的 OAuth 2.0 客户端 ID client_secret.json 运行它,我收到错误 ValueError: Client secrets must be for a web or installed app.。此外,googleapiclient 库不能完全与 Google Photos API 配合使用。
    • @KFunk 感谢您的回复。很遗憾,我无法理解您的回复。这是因为我的英语水平不好。我对此深表歉意。我认为您想从您的问题和脚本中使用 OAuth2。我的理解正确吗?我也无法理解该错误,因为在我的环境中,我可以确认脚本有效。您能否提供复制问题的详细流程?借此,我想确认一下。如果您能合作解决您的问题,我很高兴。
    • 我的错误。我正在混淆我的凭据文件。谷歌将这些凭证文件称为credentials.json/client_secret.json,无论它是否用于oauth or a service account key,这令人困惑。对我来说仍然存在的问题是 google-api-python-client 不能完全与 Google Photos API 一起使用。我想我需要提出这些请求,并使用 requests 库进行身份验证。
    • @KFunk 感谢您的回复。不幸的是,我无法理解The issue that still remains for me is that google-api-python-client doesn't fully work with Google Photos API.。可以问一下你现在的情况吗?当您使用我的示例脚本时,是否会出现错误?因为当我使用它时,我可以确认脚本有效。所以我想确认您当前的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2021-06-15
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2013-06-07
    • 2018-12-22
    相关资源
    最近更新 更多