【问题标题】:AWS Lambda Layers - module 'dicttoxml' has no attribute 'dicttoxml'AWS Lambda 层 - 模块“dicttoxml”没有属性“dicttoxml”
【发布时间】:2021-01-07 06:25:45
【问题描述】:

我有一个基于 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

我很疑惑,这里有什么问题?

【问题讨论】:

  • 你是如何创建图层的?似乎格式不正确。
  • 是的,我创建了图层并附加到函数
  • 我提供了如何正确创建这样一个图层的步骤。如果您发现答案有帮助,我们将不胜感激。另外,如果您有任何问题,请随时提出。

标签: python-3.x amazon-web-services aws-lambda aws-lambda-layers


【解决方案1】:

我使用dicttoxml 创建了自定义层,可以确认它可以工作

使用的技术包括最近 AWS 博客中描述的 docker 工具

因此对于这个问题,我验证了如下:

  1. 创建空文件夹,例如mylayer.

  2. 进入文件夹并创建requirements.txt文件,内容为

echo dicttoxml > ./requirements.txt
  1. 运行以下 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"
  1. 将层创建为 zip:
zip -9 -r mylayer.zip python 
  1. 在 AWS 控制台中基于 mylayer.zip 创建 lambda 层。不要忘记将Compatible runtimes 指定为python3.7

  2. 使用以下 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']

【讨论】:

  • 谢谢@Marcin,我使用了错误的目录结构。
猜你喜欢
  • 2020-03-17
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
  • 2021-08-04
相关资源
最近更新 更多