Azure Function未关闭连接,处于睡眠状态未结束
我正在使用一个Python V1的Azure函数应用,它可以接收HTTP请求并处理这些请求。不过,我遇到了一个问题,就是这个函数似乎没有正确关闭连接。相反,它看起来像是在“睡觉”,没有按预期完成。
这是它接收到的请求类型的一个例子:
这是我在init.py文件中的主要函数:
import logging
from datetime import datetime
import azure.functions as func
def main(
req: func.HttpRequest,
tabproductsOldCategory: func.Out[func.SqlRow],
tabproducts: func.Out[func.SqlRow],
) -> func.HttpResponse:
logging.info(
"Python HTTP trigger and SQL output binding function processed a request."
)
try:
products = []
OldCategory = []
req_body = req.get_json()
for item in req_body:
if "num_pd" in item.keys():
products.append(item)
elif "num_sq" in item.keys():
OldCategory.append(item)
else:
logging.error("Missing necessary fields: num_pd or num_sq")
return func.HttpResponse(
"Missing necessary fields: num_pd or num_sq", status_code=400
)
logging.info(f"Processed request body. Found {len(products)} products and {len(OldCategory)} OldCategory.")
rows_products = None
rows_OldCategory = None
if len(products) > 0:
rows_products = func.SqlRowList(
map(lambda r: func.SqlRow.from_dict(r), products)
)
logging.info(rows_products)
if len(OldCategory) > 0:
rows_OldCategory = func.SqlRowList(
map(lambda r: func.SqlRow.from_dict(r), OldCategory)
)
logging.info(rows_OldCategory)
except Exception as e:
logging.error(f"An error occurred: {e}")
return func.HttpResponse(
"An error occurred while processing your request.", status_code=500
)
try:
if isinstance(rows_products, func.SqlRowList):
logging.info("UPSERTING products")
tabproducts.set(rows_products)
logging.info("products UPSERTED")
if isinstance(rows_OldCategory, func.SqlRowList):
logging.info("UPSERTING OldCategory")
tabproductsOldCategory.set(rows_OldCategory)
logging.info("OldCategory UPSERTED")
return func.HttpResponse(
body=req.get_body(),
status_code=201,
mimetype="application/json",
)
except Exception as e:
logging.info("An error occurred while upserting the rows into the SQL tables.")
logging.error(f"Exception: {e}")
return func.HttpResponse(f"Error processing request: {e}", status_code=400)
我面临的问题是,这个函数似乎没有正确关闭连接。它看起来像是在“睡觉”,没有按预期完成。我不太明白为什么会这样,也不知道该怎么解决。如果有人能提供一些见解或建议,我将非常感激。
我尝试在我的Azure函数应用中处理HTTP请求。我本来希望这个函数能处理请求,适当地处理请求中的num_sq或num_pd字段,更新数据库,然后关闭连接。然而,似乎这个函数没有按预期关闭连接,反而像是在“睡觉”,没有完成。
我的function.json文件内容:
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
},
{
"name": "tabproductsOldCategory",
"type": "sql",
"direction": "out",
"commandText": "external_source.tab_products_old_category",
"connectionStringSetting": "SQLConnectionString"
},
{
"name": "tabproducts",
"type": "sql",
"direction": "out",
"commandText": "external_source.tab_products",
"connectionStringSetting": "SQLConnectionString"
}
]
}
host.json文件内容:
{
"version": "2.0",
"functionTimeout": "00:05:00"
},
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
},
"fileLoggingMode": "debugOnly",
"logLevel": {
"Function.my-func": "Information",
"default": "None"
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
1 个回答
0
一般来说,Azure Functions 会自动处理连接的打开和关闭,所以你不需要手动关闭与外部资源(比如数据库)的连接。
- 可以试着使用 finally 块来关闭连接。
- 在
host.json
文件中设置超时选项"functionTimeout":"00:20:00"
。
我原本期待这个函数能处理请求,适当地处理请求中的 num_sq 或 num_pd 字段,然后在数据库中进行插入或更新,最后关闭连接。
我在我的环境中复现了你的需求。
- 在我的 SQL 数据库中创建了两个表
tabproductsOldCategory
和tabproducts
。
代码片段:
def main(req: func.HttpRequest, tabproductsOldCategory: func.Out[func.SqlRow], tabproducts: func.Out[func.SqlRow]) -> func.HttpResponse:
logging.info("Python HTTP trigger and SQL output binding function processed a request.")
try:
req_body = req.get_json()
products = [item for item in req_body if "num_pd" in item.keys()]
OldCategory = [item for item in req_body if "num_sq" in item.keys()]
logging.info(f"Processed request body. Found {len(products)} products and {len(OldCategory)} OldCategory.")
rows_products = func.SqlRowList(map(func.SqlRow.from_dict, products))
rows_OldCategory = func.SqlRowList(map(func.SqlRow.from_dict, OldCategory))
except Exception as e:
logging.error(f"An error occurred: {e}")
return func.HttpResponse("An error occurred while processing your request.", status_code=500)
try:
if rows_products:
logging.info("UPSERTING products")
tabproducts.set(rows_products)
logging.info("products UPSERTED")
if rows_OldCategory:
logging.info("UPSERTING OldCategory")
tabproductsOldCategory.set(rows_OldCategory)
logging.info("OldCategory UPSERTED")
return func.HttpResponse(
body=req.get_body(),
status_code=201,
mimetype="application/json",
)
except Exception as e:
logging.error("An error occurred while upserting the rows into the SQL tables.")
logging.error(f"Exception: {e}")
return func.HttpResponse(f"Error processing request: {e}", status_code=400)
local.settings.json:
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "python",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"SqlConnectionString":"<Sql_connection_string>"
}
}
function.json:
{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"post"
],
"authLevel": "anonymous"
},
{
"type": "http",
"direction": "out",
"name": "$return"
},
{
"name": "tabproductsOldCategory",
"type": "sql",
"direction": "out",
"connectionStringSetting": "SqlConnectionString",
"commandText": "dbo.tabproductsOldCategory"
},
{
"name": "tabproducts",
"type": "sql",
"direction": "out",
"connectionStringSetting": "SqlConnectionString",
"commandText": "dbo.tabproducts"
}
],
"disabled": false
}
- 通过 POSTMAN 发送数据作为 POST 请求,向 SQL 数据库插入数据:
控制台输出:
(env) c:\Users\uname\httpfn>func start
Found Python version 3.11.8 (py).
Azure Functions Core Tools
Core Tools Version: 4.0.5455 Commit hash: N/A (64-bit)
Function Runtime Version: 4.27.5.21554
[2024-03-06T10:21:29.718Z] Customer packages not in sys path. This should never happen!
[2024-03-06T10:21:34.979Z] Worker process started and initialized.
Functions:
HttpTrigger: [POST] http://localhost:7071/api/HttpTrigger
For detailed output, run func with --verbose flag.
[2024-03-06T10:21:40.023Z] Host lock lease acquired by instance ID '000000000000000000000000F72731CC'.
[2024-03-06T10:34:58.025Z] Executing 'Functions.HttpTrigger' (Reason='This function was programmatically called via the host APIs.', Id=e257de76-0e5a-44a6-8a7e-1b9e3e0066b5)
[2024-03-06T10:34:58.151Z] UPSERTING OldCategory
[2024-03-06T10:34:58.151Z] Python HTTP trigger and SQL output binding function processed a request.
[2024-03-06T10:34:58.151Z] Processed request body. Found 1 products and 1 OldCategory.
[2024-03-06T10:34:58.151Z] UPSERTING products
[2024-03-06T10:34:58.151Z] products UPSERTED
[2024-03-06T10:34:58.151Z] OldCategory UPSERTED
[2024-03-06T10:35:07.602Z] Executed 'Functions.HttpTrigger' (Succeeded, Id=e257de76-0e5a-44a6-8a7e-1b9e3e0066b5, Duration=9538ms)
门户:
- 数据插入成功。
tabproducts 表:
tabproductsOldCategory 表: