[英]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.