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

如何在AWS Lambda主处理程序中同时处理协程与常规函数?

问题:AWS Lambda中区分调用同步函数与异步协程函数

开发部署在API网关后的AWS Lambda应用时,路由映射中同时包含常规同步函数和异步协程函数,原代码统一使用await调用所有路由函数,导致同步函数调用失败。需要在主处理逻辑中区分两种函数的调用方式:直接执行同步函数,用await调用协程函数。

原代码问题示例

原主处理代码如下,当路由指向同步函数时,await会触发错误:

# 映射不同路径到对应处理函数
main_router = {}
main_router.update(first_router)
main_router.update(second_router)


async def main(event):
    try:
        payload = {}
        resource = event['resource']
        payload['resource'] = resource
        payload['path'] = event['path']
        payload['method'] = event['httpMethod']
        body = event.get('body')
        query_params = event.get('queryStringParameters')
        if body:
            payload.update(body)
        if query_params:
            payload.update(query_params)

        if resource in main_router:
            # 统一用await调用,同步函数会报错
            return await main_router[resource](payload)
        return "not in main router"
    except Exception as e:
        return str(e)


def lambda_handler(event, _context):
    return asyncio.run(main(event))

示例路由包含两种类型的函数:

postmortems_router = {
    "/services": get_services,  # 常规同步函数
    "/services/{proxy+}": get_specific_service, # 异步协程函数
}

解决方案:使用inspect模块判断函数类型

通过Python标准库的inspect模块,用iscoroutinefunction方法判断目标函数是否为协程函数,从而选择对应的调用方式:

  1. 导入inspect模块
  2. 在调用路由函数前增加判断逻辑

修改后的main函数核心代码:

import inspect

# ... 其他代码保持不变 ...

if resource in main_router:
    handler_func = main_router[resource]
    if inspect.iscoroutinefunction(handler_func):
        return await handler_func(payload)
    else:
        return handler_func(payload)

注意事项

Lambda入口函数lambda_handler无需修改,保持return asyncio.run(main(event))即可正常运行,后续若有问题可再调整。

内容的提问来源于stack exchange,提问作者brightstar2100

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 23:42:04