VOOZH about

URL: https://repost.aws/questions/QU-wQeTkbtQvatbKto_xU7tw/runtime-importmoduleerror-with-lambda-and-python-docx

⇱ Runtime.ImportModuleError with Lambda and python-docx | AWS re:Post


Skip to content

Runtime.ImportModuleError with Lambda and python-docx

0

Hi, I have created a lambda layer. I uploaded a zip having python/{python-docs} files. I have added this lambda layer to my AWS lambda. While testing lambda, I am getting below error Runtime.ImportModuleError: Unable to import module 'lambda_function': cannot import name 'etree' from 'lxml' (/opt/python/lxml/init.py)

this comes at the first line of import from docx import Document

is there any way to fix this? I don't want to go the container way.

Language
English

asked 2 years ago1.2K views

2 Answers
  • Newest
  • Most votes
  • Most comments
Are these answers helpful? Upvote the correct answer to help the community benefit from your knowledge.
0

Hi,

  1. Did the lib run successfully on your local env?
  2. Base the error msg, you can check the lxml which did contain the 'etree'.
  3. You can change your import code snip to "import lxml" to observe whether the function can work. if it can run without error, this indicates that your layer is right for lambda but the module is wrong such as the 'lxml' did not contain 'etree' and so on and then you need to adjust the zip file.

answered 2 years ago

0

This is because if python docx has some OS dependent libraries and might not work if you zip it on your local and then add it as layer. Here is something that worked for me and I thought was the easiest way to get around such problems.

This is an alternative approach that helped me fixed this issue without spinning an ec2 instance. For reference, I was getting the same issue with my Lambda function when I was using the python-docx library.

The easiest way is to utilize your cloud shell environment. The AWs cloud shell had a similar runtime environment as my python lambda. You can pip install your libraries, package them as you would traditionally do for a normal zip file and then the AWS cloud shell has an option to download the zip file to your local desktop. You can download it and then upload the zip file to your lambda layer and use it as a dependency. Worked well for me and saves me the hassle of spinning a VM every time. Few things to note would be:

The python version on your cloud shell might not be the same as the version on your lambda, but it very easy to upgrade/downgrade it on your cloud shell before you use it. The initial zip file that I created had a folder named python-3.12.x but it did not work with that, but renaming it 3.12 worked. Hope this helps!

answered 2 years ago