在没有配置文件的情况下验证google API

2024-03-29 11:52:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在没有配置文件的情况下验证GoogleAPI,我甚至找不到证据证明这是可能的,除了我的服务中多年没有使用过的旧代码

我的班级收到这条命令:

   self._connection_data = {
        "type": args,
        "project_id": args,
        "private_key_id": args,
        "private_key": args,
        "client_email": args,
        "client_id": args,
        "auth_uri": args,
        "token_uri": args,
        "auth_provider_x509_cert_url": args,
        "client_x509_cert_url": args
    }

该守则是—

   from google.cloud import bigquery
   from google.oauth2 import service_account

   def _get_client(self):

        credentials = service_account.Credentials.from_service_account_info(self._connection_data)
        return bigquery.Client(project=self._project_id, credentials=credentials, location='US')

我收到了错误

'{"error":"invalid_grant","error_description":"Invalid grant: account not found"}

但是,当我为配置使用一个名为config.json的帮助文件和一个OS environmentnt变量时,一切都正常:

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "config.json"
self.job_config = bigquery.QueryJobConfig()
self.job_config.use_legacy_sql = True

return bigquery.Client()

我不想要一个带有env变量的解决方案,我希望使用没有文件路径的Credentials类


Tags: keyfromselfprojectclientidconfigdata
2条回答

最后,我成功地使代码工作起来,而不需要全局变量或文件路径。我配置的凭据有问题

这是守则-

# init class here
    self.job_config = bigquery.QueryJobConfig()
    self.job_config.use_legacy_sql = True

def _get_client(self):
    credentials = service_account.Credentials.from_service_account_info(self._connection_data)
    return bigquery.Client(project=self._project_id, credentials=credentials)

 # function to get columns 
        query_job = self._get_client().query(query, job_config=self.job_config)
        results = query_job.result(timeout=self._current_timeout)

我唯一缺少的部分是在所有查询中发送将遗留SQL设置为true的QueryJobConfig类

不幸的是,没有其他方法可以在不使用环境变量或指定密钥文件路径的情况下对API请求进行身份验证。有一些方法可以使用密钥json文件通过GCP验证您的请求。在做任何事情之前,您应该设置您的服务帐户并下载带有密钥的json文件,如here所述

然后,根据documentation,第一种方法使用默认凭证:

If you don't specify credentials when constructing the client, the client library will look for credentials in the environment.

这意味着,您只需要设置环境变量。然后,Google客户端库将隐式地确定凭据。此外,它还允许您在应用程序之外单独提供凭据,这简化了对代码进行更改的过程。可以按如下方式设置环境变量:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

设置后,您将能够运行以下code

def implicit():
    from google.cloud import storage

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    storage_client = storage.Client()

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

其次,可以使用[google.oauth2.service_account][3]模块在代码中指定文件路径。报告指出:

An OAuth 2.0 client identifies the application and lets end users authenticate your application with Google. It allows your application to access Google Cloud APIs on behalf of the end user.

要使用该模块,您可以使用以下两种代码之一:

#It creates credentials using your .json file and the Credentials.from_service_account_file constructor
credentials = service_account.Credentials.from_service_account_file(
    'service-account.json')

#If you set the environment variable, you can also use
#info = json.loads(os.environ['GOOGLE_APPLICATION_CREDENTIALS_JSON_STRING'])
#Otherwise, you specify the path inside json.load() as below
service_account_info = json.load(open('service_account.json'))
credentials = service_account.Credentials.from_service_account_info(
    service_account_info)

最后,我鼓励您检查documentation中的身份验证策略

相关问题 更多 >