繁体   English   中英

验证 BigQuery 表是否存在

[英]Verify BigQuery table existence

我有一个简单的函数来确定表是否存在:

def check_users_usersmetadata_existence():
    """
    Checks if the table Prod_UserUserMetadata exists
    """
    app_id = get_app_id()
    bigquery_client = bigquery.Client(project=app_id)
    dataset_ref = bigquery_client.dataset('Backup')
    table_ref = dataset_ref.table('Prod_UserUserMetadata')
    try:
        table = bigquery_client.get_table(table_ref)
        if table:
            print('Table {}\'s existence sucessfully proved!'.format(table_ref))
            return True
    except HttpError as error:
        raise
        print('Whoops! Table {} doesn\'t exist here! Ref: {}'.format(table_ref, error.resp.status))
        return False

问题是,它会在此行table = bigquery_client.get_table(table_ref)上抛出 404,这是可以的,因为该表不应该存在。 但它不会继续处理脚本的其余部分。 我试图在try except解析它, try except包装器,但它不起作用。 我将如何解析这个?

您的脚本没有输入异常子句,因为它引发了NotFound错误而不是HttpError

这应该有效:

from google.cloud.exceptions import NotFound
def check_users_usersmetadata_existence():
    # (...)
    try:
        table = bigquery_client.get_table(table_ref)
        if table:
            print('Table {}\'s existence sucessfully proved!'.format(table_ref))
            return True
    except NotFound as error:
        # ...do some processing ...
        print('Whoops! Table {} doesn\'t exist here! Ref: {}'.format(table_ref, error.resp.status))
        return False

参见BigQuery Python客户端官方文档中的示例: https : //googleapis.dev/python/bigquery/latest/usage/tables.html#getting-a-table

摘抄:

from google.cloud import bigquery
from google.cloud.exceptions import NotFound

client = bigquery.Client()
# table_id = "your-project.your_dataset.your_table"

try:
    client.get_table(table_id)  # Make an API request.
    print("Table {} already exists.".format(table_id))
except NotFound:
    print("Table {} is not found.".format(table_id))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM