Google Api客户端-AttributeError:'str'对象没有属性'authorize'

问题描述 投票:0回答:1

我的代码一直在工作,直到我决定将我的Google Api凭据移到我的Docker环境中。我正在使用Flask作为网络服务器框架。

这是我的设置:

DOCKER:

docker-compose-dev.yml

environment:
  - FLASK_ENV=development
  - APP_SETTINGS=project.config.DevelopmentConfig
  - GOOGLE_APPLICATION_CREDENTIALS=/usr/src/app/project/api/resources/youtube/urls/project-84a0ef4dcd33.json  

FLASK:

config.py

 class DevelopmentConfig(BaseConfig):
    CREDENTIALS = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')
    YOUTUBE_API_SERVICE_NAME = "youtube"
    YOUTUBE_API_VERSION = "v3"

video.py

from project.config import DevelopmentConfig

CREDENTIALS = DevelopmentConfig.CREDENTIALS
YOUTUBE_API_SERVICE_NAME = DevelopmentConfig.YOUTUBE_API_SERVICE_NAME
YOUTUBE_API_VERSION = DevelopmentConfig.YOUTUBE_API_VERSION

def youtube_id(track_name):
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, credentials=CREDENTIALS,
    developerKey=None)

    search_response = youtube.search().list(
    q=track_name,
    part="id,snippet",
    ).execute()

    videos = []
    videos_ids = []
    channels = []
    playlists = []

    for search_result in search_response.get("items", []):
        if search_result["id"]["kind"] == "youtube#video":
            videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                 search_result["id"]["videoId"]))
            videos_ids.append("%s" % (search_result["id"]["videoId"]))
        elif search_result["id"]["kind"] == "youtube#channel":
            channels.append("%s (%s)" % (search_result["snippet"]["title"],
                                   search_result["id"]["channelId"]))
        elif search_result["id"]["kind"] == "youtube#playlist":
            playlists.append("%s (%s)" % (search_result["snippet"]["title"],
                                    search_result["id"]["playlistId"]))

    return videos_ids[0]

现在我遇到以下错误:

AttributeError: 'str' object has no attribute 'authorize'

怎么了,我想念什么?

flask docker-compose youtube-api google-api-client
1个回答
0
投票

project_xxxxx.json环境中设置的docker的路径(“字符串”)必须传递到service_account.Credentials.from_service_account_file()

为了清楚起见,请在config.py中更改变量名称:

PATH_TO_CREDENTIALS = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')

然后,将service_account导入到您的video.py模块中,如下所示:

from google.oauth2 import service_account

和:

GET_CREDENTIALS = DevelopmentConfig.PATH_TO_CREDENTIALS
PASS_CREDENTIALS = service_account.Credentials.from_service_account_file(GET_CREDENTIALS)

最后,像这样传递凭据:

youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, credentials=PASS_CREDENTIALS,
    developerKey=None)

这将起作用。

© www.soinside.com 2019 - 2024. All rights reserved.