首页 > 解决方案 > 基于 Google Discovery 的 API :: 无法创建 API 客户端(SCOPES 错误)

问题描述

我正在尝试构建自定义挂钩,以便连接到仅受Google API 客户端库支持的 Google API (不幸的是,谷歌云客户端库不支持!)

这是我对服务的身份验证部分的代码:

class MyGoogleDiscoveryServiceHook(GoogleCloudBaseHook):
    client = None
    serviceName = "analyticsreporting"
    version = "v4"
    def __init__(self, conn_id = None, delegate_to = None):
        super().__init__(conn_id,delegate_to)
        self.conn_id = self.get_connection("google_analytics")
        self.extras = self.conn_id.extra_dejson
        self.KEY_FILE_LOC = self.extras.get("extra__google_cloud_platform__key_path")
        self.SCOPES = self.extras.get("extra__google_cloud_platform__scope")

    def get_conn(self):
        if not self.client:
            from google.oauth2 import service_account
            credentials = service_account.Credentials.from_service_account_file(filename = self.KEY_FILE_LOC,
                                         scopes = self.SCOPES)
            from googleapiclient.errors import Error
            self.client = build(self.serviceName, self.version,
                                #http=http_authorized,
                                #credentials = None,
                                http=None,
                                credentials = credentials,
                                cache_discovery=False,
                                )
        return self.client 

但是,当我在自定义运算符中使用此钩子时,出现错误:

[2019-12-10 21:43:41,577] {taskinstance.py:1058} 错误 - ('invalid_scope: h 不是有效的受众字符串。', '{\n "error": "invalid_scope",\n " error_description": "h 不是有效的受众字符串。"\n}')

我很确定,在 Airflow Connections 设置中,我输入了正确https://www.googleapis.com/auth/analytics.readonly的范围,并且 DAG 正在从 Airflow Connection 字符串中正确读取范围。

谁能建议这里有什么问题?

提前致谢!

UPDATE-1:附加气流连接: 在此处输入图像描述

标签: python-3.xgoogle-apigoogle-oauthairflow

解决方案


我的猜测是scopes您从 extras 中获得的值是纯字符串,而不是元组/列表。GoogleCloudBaseHook提示预期格式的默认范围值( https://github.com/apache/airflow/blob/1.10.5/airflow/contrib/hooks/gcp_api_base_hook.py#L37):

_DEFAULT_SCOPES = ('https://www.googleapis.com/auth/cloud-platform',)

错误消息进一步强化了这一点,因为它似乎试图访问您传入的索引零,在您的字符串的情况下,这是h错误所抱怨的。


推荐阅读