[英]How to catch an Exception thrown by Azure Table in Python Azure Function
I have an Azure Function HTTP triggered function written in Python 3.8.我有一个用 Python 3.8 编写的 Azure 函数 HTTP 触发函数。 This function receives an incoming HTTP request and writes an entity to an Azure Table.此函数接收传入的 HTTP 请求并将实体写入 Azure 表。 If an incoming request tries to create a duplicate entry, Azure Table throws an EntityAlreadyExists
error to the Azure Function runner.如果传入请求尝试创建重复条目,Azure 表会向 Azure 函数运行程序抛出EntityAlreadyExists
错误。 I would like to catch this exception and handle it accordingly.我想捕获这个异常并相应地处理它。
Can I catch this exception in python using a try
/ except
block from within the Azure Function?我可以使用Azure 函数中的try
/ except
块在 python 中捕获此异常吗? If so, how?如果是这样,如何? If not, do you know why?如果没有,你知道为什么吗?
try
to run code, then except ValueError as err:
to handle exception try
运行代码,然后except ValueError as err:
to handle exceptiontry
to run code, then except Exception as err:
to handle exception try
运行代码,然后将except Exception as err:
处理异常try
to run code, then except EntityAlreadyExists as err:
to handle exception try
运行代码,然后except EntityAlreadyExists as err:
处理异常None of these were successful at catching the exception being thrown from Azure Table for a duplicate entry attempt.这些都没有成功捕获从 Azure 表抛出的重复条目尝试的异常。
This is the error I am trying to catch from within my HTTP-triggered Azure Function这是我试图从 HTTP 触发的 Azure 函数中捕获的错误
Executed 'Functions.myTable' (Failed, Id=xxx-xxx-xxx-xxx, Duration=1256ms)
System.Private.CoreLib: Exception while executing function: Functions.myTable. Microsoft.Azure.WebJobs.Host: Error while handling parameter _binder after function returned:. Microsoft.Azure.WebJobs.Extensions.Storage: The specified entity already exists.
RequestId:xxx-xxx-xxx-xxx
Time:2020-09-30T13:16:00.9339049Z (HTTP status code 409: EntityAlreadyExists. The specified entity already exists.
RequestId:xxx-xxx-xxx-xxx
Time:2020-09-30T13:16:00.9339049Z). Microsoft.WindowsAzure.Storage: The specified entity already exists.
RequestId:xxx-xxx-xxx-xxx
Time:2020-09-30T13:16:00.9339049Z.
Below is relevant portions of the py file for the Azure function.下面是 Azure 函数的 py 文件的相关部分。 The question surrounds the try
/ except
block in Lines 16-27 (line numbers not shown).问题围绕第 16-27 行中的try
/ except
块(行号未显示)。
import logging
import json
import azure.functions as func
def main(req: func.HttpRequest, myTable: func.Out[str]) -> func.HttpResponse:
body = req.get_json()
data = { # Data to send to Azure Table
"PartitionKey": body.get('var1'),
"RowKey": body.get('var2'),
"Property1" : body.get('var3'),
"Property2" : body.get('var4')
}
try: # Try to send record to Azure Table
myTable.set(json.dumps(data))
except ValueError as err: # Respond with 409 if duplicate record
logging.error(err)
return func.HttpResponse(
body=f'Record already exists.',
status_code=409
)
else: # Otherwise, respond with 201 success
return func.HttpResponse(
body=f'Success.',
status_code=201
)
Below are the triggers and bindings json for the Azure function.以下是 Azure 函数的触发器和绑定 json。
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"post"
]
},
{
"name": "myTable",
"type": "table",
"tableName": "myTable",
"connection": "AzureWebJobsStorage",
"direction": "out"
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
If you are using python.如果您使用的是python。 Python can only use declarative binding mode, but not imperative binding mode, so if you want to use binding to achieve, it is impossible to use'try catch'. Python 只能使用声明式绑定模式,而不能使用命令式绑定模式,所以如果要使用绑定来实现,就不可能使用'try catch'。
The right way is put the logic in the content of the function and then you can use try catch.正确的方法是将逻辑放在函数的内容中,然后您可以使用try catch。
Azure Table Storage has a new python library in preview release that is available for installation via pip. Azure 表存储在预览版中有一个新的 Python 库,可通过 pip 安装。 To install use the following pip command要安装使用以下 pip 命令
pip install azure-data-tables
Within Azure Functions you can use a try
/ except
block to catch exceptions thrown by a Tables response.在 Azure Functions 中,您可以使用try
/ except
块来捕获 Tables 响应引发的异常。 The recommended way to access your Tables account from an Azure Functions is through an MSI enabled KeyVault client to retrieve your credential to authenticate your TableClient.从 Azure Functions 访问 Tables 帐户的推荐方法是通过启用 MSI 的 KeyVault 客户端来检索凭据以对 TableClient 进行身份验证。 An example function that tries to create a new table would look like:尝试创建新表的示例函数如下所示:
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
from azure.identity import ManagedIdentityCredential
from azure.keyvault.secrets import SecretClient
credential = ManagedIdentityCredential()
client = SecretClient("https://tablesfunctions.vault.azure.net", credential)
conn_str = client.get_secret("tables-connstr")
from azure.data.tables import TableClient
from azure.core.exceptions import ResourceExistsError
table_client = TableClient.from_connection_string(conn_str, table_name="MyTableName")
try:
table_client.create_table()
except ResourceExistsError:
return func.HttpResponse("Table already exists")
(FYI I work on the Azure SDK for Python team.) (仅供参考,我在 Azure SDK for Python 团队工作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.