【问题标题】:set gcp service key json file at runtime for rest api在运行时为rest api设置gcp服务密钥json文件
【发布时间】:2021-11-03 06:45:28
【问题描述】:

我想在运行时通过邮递员设置我的 google json 凭据文件。我做了一个 bigquery 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 才能获取大查询数据。 我希望邮递员在运行时将 key.json 文件传递​​给代码。

【问题讨论】:

  • 1) 您问题中的代码不使用/不需要服务帐户。 2) 在您的 Python 代码中设置环境变量只会影响您的 Python 代码或其子进程。 3)你提到 s 编译时错误。错误是什么? 4)邮递员与您的问题有什么关系?使用详细信息编辑您的问题。
  • @JohnHanley 希望我已经回答了您的所有疑问。希望你有一些答案。
  • 不是直接回答你的问题,但是你也可以在创建BQ客户端的时候直接传JSON文件。见this doc。请注意,它适用于 GCStorage,但也适用于 BQ,因为客户端库的身份验证是相同的。
  • @EdoAkse 在您的建议中,我们也必须在代码本身中设置密钥,这不是我的要求。我想在运行时传递密钥文件。

标签: python rest google-cloud-platform google-bigquery postman


【解决方案1】:

除了设置 env 变量,还有 2 个其他选项:

  1. 按照documentation使用client = bigquery.Client.from_service_account_json(json_credentials_path)创建客户端。
  2. 按照documentation使用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)

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多