在运行时为rest api设置GCP服务密钥json文件



我想通过邮差在运行时设置我的google json凭证文件。我做了一个大查询rest api。现在我在代码中像这样传递它:

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'C:/Users/Documents/bigQuery/service.json'
@app.route('/', methods=['GET', 'POST'])
def get_request():
query:
.
.
.
return results
if __name__ == "__main__":
app.run()

我尝试在邮差方法中从表单数据输入,但代码抛出编译时错误,要求首先设置凭据文件。

编译错误:

DefaultCredentialsError: Could not automatically determine credentials.
Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see
https://cloud.google.com/docs/authentication/getting-started

设置GOOGLE_APPLICATION_CREDENTIALS是代码获取大查询数据所必需的。我需要邮递员把钥匙递给我。

除了设置env变量,还有另外两个选项:

  1. 根据文档使用client = bigquery.Client.from_service_account_json(json_credentials_path)创建客户端。
  2. 根据文档使用client = bigquery.Client.from_service_account_info(json_object)创建客户端。

这两种方式都允许您在运行时传递凭据。第二个选项请参见下面的示例。第一个选项应该是相当明显的。

您可以在下面的代码中看到,凭证是在客户端设置的,而不是在服务器端。

server.py

from google.cloud import bigquery
from flask import Flask, request
import json

app = Flask(__name__)

def querysomething(json_object):
# https://googleapis.dev/python/bigquery/latest/generated/google.cloud.bigquery.client.Client.html#google.cloud.bigquery.client.Client.from_service_account_info
client = bigquery.Client.from_service_account_info(json_object)
# example below stolen from:
# https://cloud.google.com/bigquery/docs/reference/libraries#using_the_client_library
query = """
SELECT name, SUM(number) as total_people
FROM `bigquery-public-data.usa_names.usa_1910_2013`
WHERE state = 'TX'
GROUP BY name, state
ORDER BY total_people DESC
LIMIT 20
"""
query_job = client.query(query)  # Make an API request.
print("The query data:")
for row in query_job:
# Row values can be accessed by field name or index.
print("name={}, count={}".format(row[0], row["total_people"]))

@app.route("/api/query", methods=["POST"])
def api_query():
print(request.is_json)
json_object = json.loads(request.get_json())
print(json_object)
querysomething(json_object)
return "ok"

if __name__ == "__main__":
app.run(debug=True)

client.py

import requests
import json

with open("credentials.json") as infile:
credentials = json.load(infile)

target = "http://127.0.0.1:5000/api/query"
asjson = json.dumps(credentials)
response = requests.post(target, json=asjson)
print(response, response.text)

相关内容

  • 没有找到相关文章

最新更新