Gettting the below error while running the lambda code, I am using the library called
from flatten_json import flatten
I tried to look for a lambda layer, but did not find any online, please let me know if any one used this before or suggest any alternative
flatten_json library is missing.
Use pip install flatten_json
to get it
There are four steps you need to do:
My answer will focus on 1. and 2. as they are what is most important to your problem. Unfortunately, packaging Python dependencies can be a bit more complicated than for other runtimes.
The main issue is that some dependencies use C code under the hood, especially performance critical libraries, for example for Machine Learning etc.
C code needs to be compiled and if you run pip install
on your machine the code will be compiled for your computer. AWS Lambdas use a linux
kernel and amd64
architecture. So if you are running pip install
on a Linux machine with AMD or Intel processor, you can indeed just use pip install
. But if you use macOS or Windows, your best bet is Docker.
pip install --target python flatten_json
zip -r layer.zip python
The lambci project provides great Docker container for building and running Lambdas. In the following example I am using their build-python3.8
image.
docker run --rm -v $(pwd):/var/task lambci/lambda:build-python3.8 pip install --target python flatten_json
zip -r layer.zip python
Be aware that $(pwd)
is meant to be your current directoy. On macOS and WSL this should work, but if it does not work you can just replace it with the absolute path to your current directory.
Those commands will install the dependency into a target folder called python
. The name is important, because it is one of two folders of a layer where Lambda looks for dependencies .
The python
folder is than archived recursively ( -r
) in a file called layer.zip
.
Your next step is to create a new Layer in AWS and associated your function with that layer.
There are two options to choose from
Option 1) You can use a deployment package to deploy your function code to Lambda.
flatten_json
as your code to the Lambda.flatten_json
Option 2) Create a layer that has the library dependencies you need, in your case just flatten_json
. And then attach that layer to your Lambda.
How to decide between 1) and 2)?
You can do this is in a Lambda if you don´t want to create the layer. Keep in mind it will run slower since it has to install the library in every run:
import sys
import subprocess
subprocess.call('pip install flatten_json -t /tmp/ --no-cache-dir'.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
sys.path.insert(1, '/tmp/')
import flatten_json
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.