[英]Verify BigQuery table existence
I have a simple function to determine whether a table exists or not:我有一个简单的函数来确定表是否存在:
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
Problem is, it throws a 404 on this line table = bigquery_client.get_table(table_ref)
which is ok because the table shouldn't exist.问题是,它会在此行
table = bigquery_client.get_table(table_ref)
上抛出 404,这是可以的,因为该表不应该存在。 But it won't continue to process the rest of the script.但它不会继续处理脚本的其余部分。 I'm trying to parse it inside a
try except
wrapper however it's not working.我试图在
try except
解析它, try except
包装器,但它不起作用。 How would I parse this?我将如何解析这个?
Your script is not entering the exception clause as it raises a NotFound
error and not a HttpError
.您的脚本没有输入异常子句,因为它引发了
NotFound
错误而不是HttpError
。
This should work:这应该有效:
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
See the example in the official documentation of the BigQuery Python client: https://googleapis.dev/python/bigquery/latest/usage/tables.html#getting-a-table参见BigQuery Python客户端官方文档中的示例: https : //googleapis.dev/python/bigquery/latest/usage/tables.html#getting-a-table
Excerpt:摘抄:
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.