Я получаю досадную ошибку при попытке выполнить устойчивую функцию Azure: ожидается, что параметр context будет иметь тип azure.functions.Context, получил <class 'azure.functions._durable_functions.OrchestrationContext'>
Код довольно прост.
import azure.functions as func
import azure.durable_functions as df
import logging
app = df.DFApp(http_auth_level=func.AuthLevel.FUNCTION)
#HTTP triggered function invoked by the client
@app.route(route = "orchestrators/{functionName}/{county}")
@app.durable_client_input(client_name = "starter")
async def HttpAsyncTest(req: func.HttpRequest, starter: str) -> func.HttpResponse:
logging.info("CleanMatchParcel HTTP trigger function processed a request.")
fname = req.route_params["functionName"]
county = req.route_params["county"]
if fname and fname.lower() in ["funca", "funcb", "funcc"]:
if not county:
return func.HttpResponse("Missing county parameter in the query string.", status_code=500)
fparams = {"county": county}
instance_id = await starter.start_new(fname, None, fparams)
logging.info(f"Started orchestration with ID = '{instance_id}'.")
response, respcode = starter.create_check_status_response(req, instance_id)
return func.HttpResponse(response, respcode)
else:
return func.HttpResponse("Pass a valid function name in the query string.", status_code=500)
@app.orchestration_trigger(context_name = "context1")
def funca(context1: df.DurableOrchestrationContext):
inputContext = context1.get_input()
reqCounty = inputContext.get("county")
#other code
return(msg, 200)
Файл function.json выглядит следующим образом:
{
"scriptFile": "function_app.py",
"bindings": [
{
"authLevel": "function",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"route": "orchestrators/{functionName}/{county}",
"methods": [
"post",
"get"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"name": "starter",
"type": "durableClient",
"direction": "in"
},
{
"name": "context1",
"type": "orchestrationTrigger",
"direction": "in"
}
]
}
Я попытался удалить декоратор триггера оркестрации, а также опустить спецификацию типа для параметра функции context1. Эти две вещи устраняют ошибку, но затем я получаю другую ошибку.
Странно то, что тот же код отлично работает в другом приложении-функции Azure, запускаемом по http.
Что может быть не так?
В модели программирования Python V2 нет отдельного файла function.json
. Все данные, связанные с привязкой, будут находиться в самом файле function_app.py
, а структура папок для модели V2 должна выглядеть, как показано ниже.
Я внес несколько изменений в ваш код и заставил его работать так, как ожидалось.
function_app.py-
import azure.functions as func
import azure.durable_functions as df
import logging
app = df.DFApp(http_auth_level=func.AuthLevel.FUNCTION)
#HTTP triggered function invoked by the client
@app.route(route = "orchestrators/{functionName}/{county?}")
@app.durable_client_input(client_name = "starter")
async def HttpAsyncTest(req: func.HttpRequest, starter: str) -> func.HttpResponse:
logging.info("CleanMatchParcel HTTP trigger function processed a request.")
fname = req.route_params["functionName"]
county = req.route_params.get("county")
if fname and fname.lower() in ["funca", "funcb", "funcc"]:
if not county:
return func.HttpResponse("Missing county parameter in the query string.", status_code=500)
fparams = {"county": county}
instance_id = await starter.start_new(fname, None, fparams)
logging.info(f"Started orchestration with ID = '{instance_id}'.")
response = starter.create_check_status_response(req, instance_id)
return response
else:
return func.HttpResponse("Pass a valid function name in the query string.", status_code=500)
@app.orchestration_trigger(context_name = "context")
def funca(context1: df.DurableOrchestrationContext):
inputContext = context1.get_input()
reqCounty = inputContext.get("county")
return (reqCounty,200)
Я получаю ожидаемый ответ при вызове функции Url.
Если параметр округа отсутствует-
Если передано неверное имя функции-
@anilcreates обратитесь к этому адресу Learn.microsoft.com/en-us/azure/azure-functions/durable/…, чтобы понять, как создается устойчивая функция v2.
@IkhtesamAfrin - Да, это та документация, о которой я говорил. Это не объясняет, почему значение context_name должно быть «контекстом». Если нет гибкости, тогда зачем вообще этот параметр? В любом случае, проблема на данный момент решена. Я принял ваш ответ.
Это сработало! Спасибо за решение. Я не понимаю, почему существует параметр context_name, если значение должно быть «контекст».