AWS Lambda读取作为源代码上传的zip文件的内容 [英] AWS Lambda read contents of file in zip uploaded as source code

查看:248
本文介绍了AWS Lambda读取作为源代码上传的zip文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件:

MyLambdaFunction.py

config.json

我将这两个压缩在一起以创建 MyLambdaFunction.zip .然后,我通过AWS控制台将其上传到我的lambda函数.

I zip those two together to create MyLambdaFunction.zip. I then upload that through the AWS console to my lambda function.

config.json 的内容是各种环境变量.我需要一种方法,每次运行lambda函数时都读取文件的内容,然后使用其中的数据来设置运行时变量.

The contents of config.json are various environmental variables. 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.

如何获取Python Lambda函数以读取文件 config.json 的内容,该文件已与源代码一起上传到了zip文件中?

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?

推荐答案

通过@helloV向正确的方向推算出来.

Figured it out with the push in the right direction from @helloV.

在python文件的顶部放置"import os"

At the top of the python file put "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:

  • 获取config.json文件的存储路径
  • 打印该路径以在CloudWatch日志中查看
  • 打开该路径下存储的文件,读取内容
  • 将内容加载到json对象中以方便导航
  • 获取json中存储的变量之一的值
  • 打印该内容以在CloudWatch日志中查看

这是config.json的样子:

Here is what the config.json looks like:

{
    "environment":"dev"
}

编辑 AWS lambda现在支持直接在控制台UI中使用环境变量.因此,如果您的用例与我的用例相同(即用于配置文件),则不再需要配置文件.

EDIT AWS lambda now supports use of environmental variables directly in the console UI. So if your use case is the same as mine (i.e. for a config file) you no longer need a config file.

这篇关于AWS Lambda读取作为源代码上传的zip文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆