我有一个简单的函数来确定表是否存在:
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
包装器内解析它,但它不起作用。我该如何解析这个?
答案 0 :(得分:5)
您的脚本未输入异常条款,因为它引发了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
答案 1 :(得分:2)
请参阅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))
答案 2 :(得分:0)
尝试使用NotFound除外 NotFound在https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/core/google/cloud/exceptions.py
中定义