AWS Lambda,python 2.7和变量生命周期

问题描述 投票:0回答:1

我发现不在主函数但在全局范围内的python指令只运行一次,在创建/更新函数之后(也许在更换容器之后但没有测试它)导致不同的行为首先发挥作用,然后是所有后续发射测试代码:

assets = []
print "======0. should be [] ========"
print(assets)   

def lambda_handler(event, context):
    global assets

    print "======l. should be [] ========"
    print(assets)   

    assets.append({
            "key": "val"
        })
    print "======2. should be [{'key': 'val'}] ========"
    print(assets)

    assets = {"data":assets}
    print "======3. should be {'data': [{'key': 'val'}]} ========"
    print(assets)

当我第一次运行该功能时(或在我更新它之后),我有:

======0. should be [] ========
[]
START RequestId: ecdf063e-51f0-11e8-9783-7f18ff8ee142 Version: $LATEST
======l. should be [] ========
[]
======2. should be [{'key': 'val'}] ========
[{'key': 'val'}]
======3. should be {'data': [{'key': 'val'}]} ========
{'data': [{'key': 'val'}]}
END RequestId: ecdf063e-51f0-11e8-9783-7f18ff8ee142 

这是我的期望,尽管我很困惑为什么输出在'START'之前开始。问题是:当我下次运行它时assets变量已经有旧值:

START RequestId: 66999707-51f1-11e8-b21a-9963eeb4aa56 Version: $LATEST
======l. should be [] ========
{'data': [{'key': 'val'}]}
'dict' object has no attribute 'append': AttributeError
Traceback (most recent call last):
  File "/var/task/test.py", line 11, in lambda_handler
    assets.append({
AttributeError: 'dict' object has no attribute 'append'

END RequestId: 66999707-51f1-11e8-b21a-9963eeb4aa56

正如你所看到的那样,没有======0. should be [] ========输出,而且变量已经有了价值。

我不是Python大师,所以我做错了什么或者它是一个错误?

python-2.7 amazon-web-services scope aws-lambda global-variables
1个回答
2
投票

当你重新运行它时,Lambda可能会也可能不会重复使用相同的功能,换句话说,某些状态可能会在运行之间遗留下来 - 你需要确保不做任何事情 - 所以如果你需要初始化一些东西,在函数本身中做 - 而不是在全局范围内。

这篇文章http://rodos.haywood.org/2015/06/lambda-functions-idempotent.html,虽然关于nodejs不是python,但几乎可以解释它。

© www.soinside.com 2019 - 2024. All rights reserved.