0
votes

Upon trying to run my code on AWS Lambda, I am getting the error "Unable to import module 'lambda_function': No module named Flask"

I have already installed python and python flask in the virtual environment and all other required libraries

import Flask
from flask import Flask
from flask import jsonify
from flask import request
from flask_pymongo import PyMongo

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'users'
app.config['MONGO_URI'] = 'mongodb://127.0.:27017/users'

mongo = PyMongo(app)

@app.route('/user', methods=['POST'])
def get_userdetail():
    user = mongo.db.users
    output = []

    for s in user.find():
        output.append({'Firstname' : s['Firstname'], 'Lastname' : 
                       s['Lastname']})
    return jsonify({'result' : output})

if __name__ == '__main__':
    app.run(debug=True)

I just expected the code to run but instead I am getting this error

1
"I have already installed python and python flask in the virtual environment..." What virtual environment? Lambda requires you to add your dependencies directly. - kungphu

1 Answers

1
votes

You need first to do some steps, so the dependencies will be installed automatically when you deploy to AWS Lambda. For example to use "serverless-python-requirements" to install the requriments.txt file. For more details, you can check this: https://medium.com/@Twistacz/flask-serverless-api-in-aws-lambda-the-easy-way-a445a8805028

I also noticed that your MONGO_URI is pointing to your local folder, and that's will not work when you deploy online. Check how to make a config file with two classes, one for production and one for development. So when you deploy, you just change to Production.

I hope that will help.