json - 以下引发模块错误的 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
解决方案
在创建 Lambda 函数时,我们需要指定一个handler,它是您代码中的一个函数,AWS Lambda 服务可以在执行给定的 Lambda 函数时调用该函数。
默认情况下,使用处理程序创建 Python Lambda 函数,lambda_function.lambda_handler
这表示服务必须调用lambda_handler
包含在lambda_function
模块中的函数。
从您收到的错误来看,它似乎handler
被错误地配置为类似的东西index.<something>
,并且由于index
您的部署包中没有调用 Python 模块,Lambda 无法导入相同的模块以开始执行。
推荐阅读
- movesense - 使用 React 本机应用程序收集 Movesense 传感器数据
- chatbot - AIML - 基于上一个主题的回答
- elasticsearch - 如何在spring data elasticsearch中实现docment的两个字段具有相同值的查询文档并进行聚合
- azure-cli - 如何使用 az monitor 为 HttpQueueLength 创建自动缩放规则
- db2 - 使用 db2 中的 Ingest Utility 从 csv 加载数据时跳过标题行
- java - com.google.code.javaparser 和 com.github.javaparser 有什么区别?
- java - ZonedDateTime 到 Instant 在 Java 8 中是正确的,但在 Java 9+ 中是 1h
- azure - 如何使用 Rest API 将文件夹和文件列表提交到 Azure DevOps 存储库?
- next.js - 顺风清除生产构建中使用的一些样式
- c - 是什么导致线程等待?