小编Gui*_*ume的帖子

在 Python 云函数中引发异常并同时返回 HTTP 错误代码的最佳方法

我在合并向我传达的两个要求时遇到了一些麻烦。

我最初的要求是处理我创建的用于将 JSON 数据插入 BigQuery 的 GCP 云函数中的异常。基本逻辑如下:

import json
import google.auth
from google.cloud import bigquery

class SomeRandomException(Exception):
    """Text explaining the purpose of this exception"""

def main(request):
    """Triggered by another HTTP request"""

    # Instantiation of BQ client
    credentials, your_project_id = google.auth.default(
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    client = bigquery.Client(credentials=credentials, project=your_project_id, )

    # JSON reading
    json_data: dict = request.get_json()

    final_message: str = ""
    table_name = "someTableName"

    for row in json_data:
        rows_to_insert: list = []                    
        rows_to_insert.append(row["data"])

        if rows_to_insert:
            errors: list = client.insert_rows_json(
                table_name, rows_to_insert, row_ids=[None] …
Run Code Online (Sandbox Code Playgroud)

exception http python-3.x google-cloud-platform google-cloud-functions

4
推荐指数
1
解决办法
2633
查看次数