Unable to import pydantic in lambda function

97 Views Asked by At

I am trying to import pydantic to a lambda via a lambda layer

and I keep getting this error

[ERROR] Runtime.ImportModuleError: Unable to import module 'main': No module named 'pydantic' Traceback (most recent call last):

The lambda uses python 3.9,Architecture x86_64, I have tried these commands separately :

  • docker run -i -v $(pwd)/layer:/app -w /app --entrypoint /bin/bash public.ecr.aws/lambda/python:3.9 -c "pip3 install --target ./python -r requirements.txt"

  • pip3 install --target layer/python -r requirements.txt --upgrade

  • docker run -i -v $(pwd)/layer:/app -w /app --user $(id -u):$(id -g) --entrypoint /bin/bash python:3.10.13-slim-bullseye -c "pip3 install --target ./python -r requirements.txt --upgrade"

  • pip install -r requirements.txt --python-version 3.9 --platform manylinux2014_x86_64 --target layer/python --only-binary=:all:

and then compress the packages zip -r layer.zip layer/python and upload the layer and import it in the lambda

and I keep getting this error

[ERROR] Runtime.ImportModuleError: Unable to import module 'main': No module named 'pydantic' Traceback (most recent call last):

1

There are 1 best solutions below

0
AR98 On

The following fixed the issue

  1. using pip install -r requirements.txt --python-version 3.9 --platform manylinux2014_x86_64 --target layer/python --only-binary=:all:
  2. make sure that the lambda python version is 3.9
  3. when creating the zip file it should be python/pydantic so it can be imported from the layer correctly