You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Python Durable Functions遇协程JSON序列化错误求助

问题解决:Azure Durable Functions中"coroutine is not JSON serializable"错误

错误原因

报错出现在response = client.create_check_status_response(req, instance_id)这行,因为**create_check_status_response是异步方法**,直接调用会返回一个协程(coroutine)对象,而函数试图将这个协程作为HttpResponse返回时,无法被JSON序列化,从而触发TypeError。

解决方案

1. 异步调用create_check_status_response

在调用该方法前添加await关键字,获取实际的HttpResponse对象。

2. 修正Activity函数的输入类型注解

Activity函数接收的是字典类型的请求体,而非字符串,需要将reqBody: str改为reqBody: dict。

修正后的完整代码

import azure.functions as func
import azure.durable_functions as df
from common_config.scripts import shared_config as sc
from xml_remit_gen import app_controller

myApp = df.DFApp(http_auth_level=func.AuthLevel.ANONYMOUS)

# Set configurations function (now synchronous)
def set_configurations(req_body):
    sc.GV_JOBCHAIN = req_body.get('GV_JOBCHAIN')
    sc.GV_XML_SPLIT_REQ = req_body.get('GV_XML_SPLIT_REQ')
    sc.GV_SKIP_THRESHOLD_LIMIT_CHECK_YN = req_body.get('GV_SKIP_THRESHOLD_LIMIT_CHECK_YN')
    sc.BATCH_SIZE = req_body.get('BATCH_SIZE')
    sc.PARAM_MINPROCESS_ID = req_body.get('INSERT_PROCESS_ID')


# HTTP-Triggered Function with a Durable Functions Client binding
@myApp.route(route="orchestrators/xml_remit_gen", methods=["POST"])
@myApp.durable_client_input(client_name="client")
async def http_xml_remit_gen(req: func.HttpRequest, client: df.DurableOrchestrationClient):
    try:
        req_body = req.get_json()
        set_configurations(req_body)  # Call the sync function
        print(req_body)
        # Assuming no additional arguments are required for start_new
        instance_id = await client.start_new("hello_orchestrator", req_body)
        # 关键修改:添加await调用异步方法
        response = await client.create_check_status_response(req, instance_id)
        return response  # 返回正确的HttpResponse对象
    except Exception as e:
        return func.HttpResponse(f"Error starting orchestration: {str(e)}", status_code=500)


# Orchestrator
@myApp.orchestration_trigger(context_name="context")
async def hello_orchestrator(context: df.DurableOrchestrationContext):
    req_body = context.get_input()
    await df.call_activity("run_xml_remit_gen", req_body)  # Pass req_body directly
    return req_body  # Not necessary to return req_body here


# Activity
@myApp.activity_trigger(input_name="reqBody")
# 修正类型注解:从str改为dict
async def run_xml_remit_gen(reqBody: dict):
    await app_controller.xml_remit_gen_main()  # Assuming this is a valid async function
    return reqBody

额外说明

  • 确保azure-durable-functions库版本是最新的,异步方法的使用是该库的规范要求。
  • 若app_controller.xml_remit_gen_main()是同步函数,需改为await asyncio.to_thread(app_controller.xml_remit_gen_main())来适配异步上下文。

内容的提问来源于stack exchange,提问作者Sh'Jil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:10:26