首页 > 解决方案 > 以下引发模块错误的 Lambda 代码有什么问题?

问题描述

使用以下代码创建一个连接到 Amazon AWS 的 API。这是我使用的亚马逊 Lambda 代码——

import boto3 import json import requests from requests_aws4auth import AWS4Auth

region = 'us-east-1' 
service = 'es'
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, 
service, session_token=credentials.token)

host = 'XXX.com'
index = 'items'
url = 'https://' + host + '/' + index + '/_search'

# Lambda execution starts here
def handler(event, context):

# Put the user query into the query DSL for more accurate search results.
# Note that certain fields are boosted (^).
query = {
    "query": {
    "multi_match": {
            "query": event['queryStringParameters']['q'],
            }
    }
}

# ES 6.x requires an explicit Content-Type header
headers = { "Content-Type": "application/json" }

# Make the signed HTTP request
r = requests.get(url, auth=awsauth, headers=headers, 
data=json.dumps(query))

# Create the response and add some extra content to support CORS
response = {
    "statusCode": 200,
    "headers": {
        "Access-Control-Allow-Origin": '*'
    },
    "isBase64Encoded": False
}

# Add the search results to the response
response['body'] = r.text
return response

这应该连接到带有端点 XXX.com 的 AWS ES 集群

尝试测试时获取输出 -

START RequestId: f640016e-e4d6-469f-b74d-838b9402968b Version: $LATEST
Unable to import module 'index': Error
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
END RequestId: f640016e-e4d6-469f-b74d-838b9402968b
REPORT RequestId: f640016e-e4d6-469f-b74d-838b9402968b  Duration: 
44.49 ms    Billed Duration: 100 ms     Memory Size: 128 MB Max 
Memory Used: 58 MB

标签: jsonaws-lambdaxmlhttprequest

解决方案


在创建 Lambda 函数时,我们需要指定一个handler,它是您代码中的一个函数,AWS Lambda 服务可以在执行给定的 Lambda 函数时调用该函数。

默认情况下,使用处理程序创建 Python Lambda 函数,lambda_function.lambda_handler这表示服务必须调用lambda_handler包含在lambda_function模块中的函数。

从您收到的错误来看,它似乎handler被错误地配置为类似的东西index.<something>,并且由于index您的部署包中没有调用 Python 模块,Lambda 无法导入相同的模块以开始执行。


推荐阅读