首页 > 解决方案 > Lambda 函数抛出一个异常说 unhashable type: 'dict': TypeError

问题描述

当我们部署以下代码中给出的 lambda 代码时出现以下错误 unhashable type: 'dict': TypeError Traceback (most recent call last): File "/var/task/lambda.py", line 69, in lambda_handler response_body TypeError : unhashable type: 'dict' unhashable type: 'dict': TypeError Traceback (last recent call last): File "/var/task/lambda.py", line 69, in lambda_handler response_body TypeError: unhashable type: 'dict'

import boto3, json, logging, os
import requests

logs = boto3.client('logs')
ssm = boto3.client('ssm')

#Define logging properties
log = logging.getLogger()
log.setLevel(os.environ.get("LOGLEVEL"))



def lambda_handler(event, context):
    #Initialize the status of the function
    status="SUCCESS"
    responseData = {}

    RequestType = event['RequestType']

    if RequestType == 'Delete' :
        #Set Return Data
        response_data = {"Message" : "Subscription filter deleted"}

        #return the response back to the S3 URL to notify CloudFormation about the code being run
        response=respond(event,context,status,response_data,None)

        #Function returns the response from the S3 URL
        response_body = {}
        response_body['Dev Response'] = json.dumps(response)

        return {
            response_body
        }

    destinationArn=os.environ['alert_lambda_arn']
    LogGroupName = event['ResourceProperties']['LogGroupName']
    log.debug("LogGroupName  :" + LogGroupName)
    ServiceName=LogGroupName[25:-14]
    log.debug("Service Name : {}".format(ServiceName))
    CommomPre = event['ResourceProperties']['CommonPre']
    log.debug("CommomPre :" + CommomPre)
    NoOfcommomTerm =int( event['ResourceProperties']['NoOfCommonTerm'])
    ServiceSpecPre = event['ResourceProperties']['ServiceSpecPre']
    log.debug("ServiceSpecPre :" + ServiceSpecPre)
    NoOfServiceSpecTerm = int (event['ResourceProperties']['NoOfServiceSpecTerm'])
  
    filterpattern=""
    filterpattern=getFilterpattern(CommomPre, NoOfcommomTerm, filterpattern)
    filterpattern=getFilterpattern(ServiceSpecPre, NoOfServiceSpecTerm, filterpattern)
    
    response = logs.put_subscription_filter(
    logGroupName=LogGroupName,
    filterName="vm-managed-" + ServiceName + "filter",
    filterPattern=filterpattern,
    destinationArn=destinationArn
    )
        
    #Set Return Data
    response_data = {"Message" : "Subscription filter created"}

    #return the response back to the S3 URL to notify CloudFormation about the code being run
    response=respond(event,context,status,response_data,None)

    #Function returns the response from the S3 URL
    response_body = {}
    response_body['Dev Response'] = json.dumps(response)
    
    return {
        response_body
    }


    
def getFilterpattern(prefix, NoOfterm, filterpattern):
    
    for i in range(0, NoOfterm):
        term= prefix + str(i+1)
        print(term)
        response = ssm.get_parameter(
        Name=term,
        )
        filterpattern=filterpattern + " " + response['Parameter']['Value']
    return filterpattern

    
def respond(event, context, responseStatus, responseData, physicalResourceId):
    #Build response payload required by CloudFormation
    responseBody = {}
    responseBody['Status'] = responseStatus
    responseBody['Reason'] = 'Details in: ' + context.log_stream_name
    responseBody['PhysicalResourceId'] = context.log_stream_name
    responseBody['StackId'] = event['StackId']
    responseBody['RequestId'] = event['RequestId']
    responseBody['LogicalResourceId'] = event['LogicalResourceId']
    responseBody['Data'] = responseData

    #Convert json object to string and log it
    json_responseBody = json.dumps(responseBody)
    log.debug("Response body: " + str(json_responseBody))

    #Set response URL
    responseUrl = event['ResponseURL']

    #Set headers for preparation for a PUT
    headers = {
    'content-type' : '',
    'content-length' : str(len(json_responseBody))
    }

    #Return the response to the signed S3 URL
    try:
        response = requests.put(responseUrl,
        data=json_responseBody,
        headers=headers)
        log.debug("Status code: " + str(response.reason))
        status="SUCCESS"
        return status
    #Defind what happens if the PUT operation fails
    except Exception as e:
        log.error("send(..) failed executing requests.put(..): " + str(e))
        status="FAILED"
        return status

标签: pythonamazon-web-servicesaws-lambdaboto3serverless

解决方案


代替:

    return {
        response_body
    }

应该有

    return response_body

推荐阅读