问题描述
我有一个基于python 3.7的AWS Lambda函数,并尝试通过AWS层使用模块dicttoxml。我的Python代码如下:
import json
import dicttoxml
def lambda_handler(event,context):
xml = dicttoxml.dicttoxml({"name": "Foo"})
return {
'statusCode': 200,'body': json.dumps('Hello from Lambda!')
}
在我的本地计算机上,它工作正常,但Lambda给出如下错误:
{
"errorMessage": "module 'dicttoxml' has no attribute 'dicttoxml'","errorType": "AttributeError","stackTrace": [
" File \"/var/task/lambda_function.py\",line 4,in lambda_handler\n xml = dicttoxml.dicttoxml({\"name\": \"Ankur\"})\n"
]
}
dicttoxml层的directory structure如下:
dicttoxml.zip> python> dicttoxml> dicttoxml.py
我很困惑,这是怎么了?
解决方法
我使用dicttoxml
创建的自定义图层可以确认其有效。
所使用的技术包括最近的 AWS博客中所述的 docker工具:
因此,对于这个问题,我验证了,如下所示:
-
创建空文件夹,例如
mylayer
。 -
转到该文件夹并创建内容为{p>的
requirements.txt
文件
echo dicttoxml > ./requirements.txt
- 运行以下docker命令:
docker run -v "$PWD":/var/task "lambci/lambda:build-python3.7" /bin/sh -c "pip install -r requirements.txt -t python/lib/python3.7/site-packages/; exit"
- 以zip格式创建图层:
zip -9 -r mylayer.zip python
-
在AWS控制台中基于
mylayer.zip
创建lambda层。不要忘记为Compatible runtimes
指定python3.7
。 -
使用以下lambda函数测试lambda中的图层:
import dicttoxml
def lambda_handler(event,context):
print(dir(dicttoxml))
该函数正确执行:
['LOG','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__spec__','__version__','collections','convert','convert_bool','convert_dict','convert_kv','convert_list','convert_none','default_item_func','dicttoxml','escape_xml','get_unique_id','get_xml_type','ids','key_is_valid_xml','logging','long','make_attrstring','make_id','make_valid_xml_name','numbers','parseString','randint','set_debug','unicode','unicode_literals','unicode_me','version','wrap_cdata']