简体   繁体   中英

How to add Python libraries in locally created SAM Lambda app?

I have created local SAM Lambda app on my machine and local MongoDB. My intention is to create a connection between SAM app and MongoDB. You can see the code:

import json
import pymongo

client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
mydb = client['Employee']
def lambda_handler(event, context):
    information = mydb.employeeInformation
    record = {
        'FirstName' : 'Rehan',
        'LastName' : 'CH',
        'Department' : "IT" 
    }
    information.insert_one(record)
    print("Record added")
    return {
        "statusCode": 200,
        "body": json.dumps(
            {
                "message": "Finally my local lambda worked.",
            
            }
        ),
    }

I have added the python library "PyMongo" using Pip install pymongo. But when I execute this SAM Lambda app, it throws an error that says:

{"errorMessage": "Unable to import module 'app': No module named 'pymongo'", "errorType": "Runtime.ImportModuleError", "requestId": "d9a99323-2331-4228-s5f6-dd2e18d6a85e", "stackTrace": []}

Although, I have added the python library to the folder as you can see in the following picture: 在此处输入图像描述

Please tell me how to add libraries in the locally created SAM app.

I have added libraries on the AWS console but in the local environment, I don't know where to add these libraries.

You need to add pymongo to the requirements.txt for each lambda function where you use the module.

It is not a standard module, nor the one preinstalled on lambda. You need to explicitly specify all such modules for SAM to include them into the lambda code.

No need to copy modules manually, let pip do the job. It will also take care of dependencies.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM