AWS Lambda PATCH请求操作DynamoDB报KeyError问题求助
PATCH请求更新DynamoDB时出现KeyError: 'path'问题
我尝试通过PATCH请求向DynamoDB更新数据,GET和POST请求均可正常工作,但执行PATCH时出现KeyError错误,提示找不到'path'字段。以下是相关信息:
错误信息
{ "errorMessage": "'path'", "errorType": "KeyError", "requestId": "2d9d09ac-9450-45ab-bbbf-36a92188179c", "stackTrace": [ " File \"/var/task/lambda_function.py\", line 22, in lambda_handler\n path = event[\"path\"]\n" ] }
Lambda代码
import boto3 import json from custom_encoder import CustomEncoder dynamodbProductTable = "prod-status" dynamodb = boto3.resource("dynamodb") prodcutTable = dynamodb.Table(dynamodbProductTable) patchMethod = "PATCH" productPath = "/product" def lambda_handler(event, context): httpMethod = event["httpMethod"] path = event["path"] if httpMethod == patchMethod and path == productPath: requestBody = json.loads(event["body"]) response = modifyProduct(requestBody["productId"], requestBody["updateKey"], requestBody["updateValue"]) else: response = buildResponse(404, "Not Found") return response def modifyProduct(productId, updateKey, updateValue): try: response = prodcutTable.update_item( Key={ "productId": productId }, UpdateExpression="set {0}s = :value".format(updateKey), ExpressionAttributeValues={ ":value": updateValue }, ReturnValues="UPDATED_NEW" ) body = { "Operation": "UPDATE", "Message": "SUCCESS", "UpdatedAttributes": response } return buildResponse(200, body) except: logger.exception("error in modifyProduct") def buildResponse(statusCode, body=None): response = { "statusCode": statusCode, "headers": { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" } } if body is not None: response["body"] = json.dumps(body, cls=CustomEncoder) return response
自定义编码器代码
import json from decimal import Decimal class CustomEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return float(obj) return json.JSONEncoder.default(self, obj)
问题解决方法
1. 安全获取event字段,避免KeyError
直接通过event["path"]访问字段会在字段缺失时抛出异常,改用event.get()方法安全获取,并添加缺失字段的处理逻辑:
修改lambda_handler函数开头代码:
def lambda_handler(event, context): httpMethod = event.get("httpMethod", "") path = event.get("path", "") # 校验必填字段是否存在 if not httpMethod or not path: return buildResponse(400, "请求参数缺失:httpMethod或path字段不存在") if httpMethod == patchMethod and path == productPath: # 安全解析请求体,避免body为空的情况 requestBody = json.loads(event.get("body", "{}")) # 校验请求体必填字段 required_fields = ["productId", "updateKey", "updateValue"] if not all(key in requestBody for key in required_fields): return buildResponse(400, f"请求体缺失必填字段:{', '.join(required_fields)}") response = modifyProduct(requestBody["productId"], requestBody["updateKey"], requestBody["updateValue"]) else: response = buildResponse(404, "Not Found") return response
2. 检查API Gateway集成配置
如果Lambda通过API Gateway触发,确保PATCH请求的集成规则和GET/POST一致:
- 确认使用Lambda代理集成:该模式下API Gateway会自动将httpMethod、path、body等请求信息封装到event中传递给Lambda,无需手动配置映射。
- 若使用自定义集成,需在PATCH请求的集成模板中添加
"path": "$context.path"配置,确保path字段被正确传入event。
3. 修复UpdateExpression的字段名错误
原代码中UpdateExpression多了一个多余的s,会导致更新的字段名错误(例如updateKey为status时,会变成statuss),修改为:
UpdateExpression="set {0} = :value".format(updateKey),
4. 修复日志模块未定义问题
modifyProduct函数中使用了logger.exception但未初始化日志模块,需在Lambda代码开头添加日志配置:
import logging logger = logging.getLogger() logger.setLevel(logging.INFO)
内容的提问来源于stack exchange,提问作者Vardhan
相关产品推荐
相关产品推荐

