<p>不幸的是,没有其他方法可以在不使用环境变量或指定密钥文件路径的情况下对API请求进行身份验证。有一些方法可以使用密钥json文件通过GCP验证您的请求。在做任何事情之前,您应该设置您的服务帐户并下载带有密钥的json文件,如<a href="https://cloud.google.com/docs/authentication/production#creating_a_service_account" rel="nofollow noreferrer">here</a>所述</p>
<p>然后,根据<a href="https://cloud.google.com/bigquery/docs/authentication/getting-started#application_default_credentials" rel="nofollow noreferrer">documentation</a>,第一种方法使用默认凭证:</p>
<blockquote>
<p>If you don't specify credentials when constructing the client, the
client library will look for credentials in the environment.</p>
</blockquote>
<p>这意味着,您只需要设置环境变量。然后,Google客户端库将隐式地确定凭据。此外,它还允许您在应用程序之外单独提供凭据,这简化了对代码进行更改的过程。可以按如下方式设置环境变量:</p>
<pre><code>export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"
</code></pre>
<p>设置后,您将能够运行以下<a href="https://cloud.google.com/docs/authentication/getting-started#verifying_authentication" rel="nofollow noreferrer">code</a>:</p>
<pre><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)
</code></pre>
<p>其次,可以使用<code>[google.oauth2.service_account][3]</code>模块在代码中指定文件路径。报告指出:</p>
<blockquote>
<p>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.</p>
</blockquote>
<p>要使用该模块,您可以使用以下两种代码之一:</p>
<pre><code>#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')
</code></pre>
<p>或</p>
<pre><code>#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)
</code></pre>
<p>最后,我鼓励您检查<a href="https://cloud.google.com/docs/authentication#authentication_strategies" rel="nofollow noreferrer">documentation</a>中的身份验证策略</p>