我的代码一直在工作,直到我决定将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
烧瓶:
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'
怎么了,我想念什么?
答案 0 :(得分:1)
在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)
这将起作用。