[英]AWS Lambda read contents of file in zip uploaded as source code
I have two files:我有两个文件:
MyLambdaFunction.py
config.json
I zip those two together to create MyLambdaFunction.zip .我 zip 这两个一起创建MyLambdaFunction.zip 。 I then upload that through the AWS console to my lambda function.然后我通过 AWS 控制台将其上传到我的 lambda function。
The contents of config.json are various environmental variables. config.json的内容是各种环境变量。 I need a way to read the contents of the file each time the lambda function runs, and then use the data inside to set run time variables.我需要一种方法来在 lambda function 每次运行时读取文件的内容,然后使用里面的数据来设置运行时变量。
How do I get my Python Lambda function to read the contents of a file, config.json , that was uploaded in the zip file with the source code?如何让我的 Python Lambda function 读取文件config.json的内容,该文件是用源代码上传到 zip 文件中的?
Figured it out with the push in the right direction from @helloV.从@helloV 向正确的方向推动来解决这个问题。
At the top of the python file put import os
在 python 文件的顶部放置import os
Inside your function handler put the following:在您的函数处理程序中放置以下内容:
configPath = os.environ['LAMBDA_TASK_ROOT'] + "/config.json"
print("Looking for config.json at " + configPath)
configContents = open(configPath).read()
configJson = json.loads(configContents)
environment = configJson['environment']
print("Environment: " + environment)
That bit right there, line by line, does the following:就在那里,一行一行,执行以下操作:
Here is what the config.json looks like:这是 config.json 的样子:
{
"environment":"dev"
}
EDIT AWS lambda now supports use of environmental variables directly in the console UI.编辑AWS lambda 现在支持直接在控制台 UI 中使用环境变量。 So if your use case is the same as mine (ie for a config file) you no longer need a config file.因此,如果您的用例与我的相同(即对于配置文件),则不再需要配置文件。
Try this.尝试这个。 The file you uploaded can be accessed like:您上传的文件可以通过以下方式访问:
import os
os.environ['LAMBDA_TASK_ROOT']/config.json
Actually, I'd rather prefer judging the context of the running lambda to determine the config it should use, instead of uploading different zip files, which is difficult to maintain.实际上,我更愿意判断正在运行的 lambda 的上下文来确定它应该使用的配置,而不是上传不同的 zip 文件,这很难维护。
lambda_configs = {
"function_name_1":{
},
"function_name_2":
{
}
}
config = lambda_configs[context.function_name]
Just done it in python3.8 lambda with simple:刚刚在 python3.8 lambda 中完成了它,简单:
with open('./dir/file.whatever') as f:
And it works just fine.它工作得很好。
import os
os.environ['LAMBDA_TASK_ROOT'] + '/config.json'
or you can use formatting或者你可以使用格式
{os.environ['LAMBDA_TASK_ROOT']}/config.json"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.