【问题标题】:Authenticate Google Cloud vision without using environment variables (set credentials by code)在不使用环境变量的情况下验证 Google Cloud 愿景(通过代码设置凭据)
【发布时间】:2020-11-03 21:52:44
【问题描述】:

我正在尝试从 AWS lambda 函数连接到 Google Cloud Vision,唯一的身份验证方法似乎是通过设置某个环境变量,有没有办法使用代码进行身份验证(我计划将凭据详细信息存储在AWS Secrets Manager 并将它们传递给 Python 中的 Google Vision 客户端)。

vision.ImageAnnotatorClient 的构造函数将 Credentials 作为第一个参数,但令人沮丧的是,我无法为一组服务帐户凭据构造这样的对象!

希望有人能提供帮助!

编辑 在这个链接中,似乎除了 Python 之外的其他语言,有一些东西可以帮助解析凭据,但没有 Python 示例!

https://cloud.google.com/docs/authentication/production#auth-cloud-explicit-python

【问题讨论】:

    标签: python amazon-web-services google-cloud-platform aws-lambda google-vision


    【解决方案1】:

    不容易找到:( 这是执行此操作的代码:

    service_account_info_string = R"""{
        "type": "service_account",
        "project_id": "",
        "private_key_id": "",
        "private_key": "-----BEGIN PRIVATE KEY-----\n.......\n-----END PRIVATE KEY-----\n",
        "client_email": "....@.....iam.gserviceaccount.com",
        "client_id": "545................45648",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/....%40....iam.gserviceaccount.com"
        }
        """
    
    service_account_info_json = json.loads(service_account_info_string)
    
    service_account_creds = creds.from_service_account_info(service_account_info_json)
    
    client = vision.ImageAnnotatorClient(credentials=service_account_creds)
    

    【讨论】:

      【解决方案2】:

      您可以将您的凭据放在service_account.json 文件中并执行以下操作:

      from google.cloud import vision
      
      client = vision.Client.from_service_account_json('service_account.json')
      

      【讨论】:

        【解决方案3】:

        我遇到了类似的问题,并通过其他答案的组合来解决。

        您需要使用来自google.oauth2service_accountcredentials.json 文件的完整路径创建一个credentials 对象。

        然后在vision.ImageAnnotatorClient 中使用这个credentials 对象。

        from google.cloud import vision
        from google.oauth2 import service_account
        
        credentials = service_account.Credentials.from_service_account_file('PATH/TO/FILE.json')
        
        client = vision.ImageAnnotatorClient(credentials=credentials)
        

        【讨论】:

          猜你喜欢
          • 2015-10-28
          • 2017-12-30
          • 2013-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-11
          • 1970-01-01
          相关资源
          最近更新 更多