Deploying Python Apps on AWS Lambda

 

Deploying Python apps on AWS Lambda is a great way to run serverless functions that scale automatically and cost only when invoked. Here's a concise guide to help you get started:


🔧 What is AWS Lambda?

AWS Lambda lets you run code without provisioning or managing servers. You simply upload your code, and Lambda takes care of everything required to run and scale your application.


2. Create Your Python Function

Example: lambda_function.py

python
def lambda_handler(event, context): return { 'statusCode': 200, 'body': 'Hello from Lambda!' }

3. Package Dependencies (if any)

If you use third-party libraries (like requests, pandas, etc.):

Option A: Use a Virtual Environment

bash
mkdir my_lambda cd my_lambda python -m venv venv source venv/bin/activate pip install requests deactivate cp -r venv/lib/python3.*/site-packages/* . cp ../lambda_function.py . zip -r my_lambda.zip .

Option B: Use Docker (to ensure Linux-compatible build)

bash
docker run -v "$PWD":/var/task lambci/lambda:build-python3.9 pip install requests -t . zip -r my_lambda.zip .

4. Create Lambda Function on AWS

Option A: Via Console

  1. Go to AWS Lambda Console.

  2. Click Create Function > Author from scratch.

  3. Upload your .zip file under "Code source".

Option B: Via AWS CLI

bash
aws lambda create-function \ --function-name my-python-func \ --runtime python3.9 \ --role arn:aws:iam::ACCOUNT_ID:role/execution-role \ --handler lambda_function.lambda_handler \ --zip-file fileb://my_lambda.zip

5. Invoke the Function

bash
aws lambda invoke --function-name my-python-func output.json cat output.json

6. Set Triggers (Optional)

  • API Gateway (to expose as a REST API)

  • S3 (trigger on file upload)

  • EventBridge, CloudWatch, etc.


7. Monitoring

Use CloudWatch Logs to monitor logs and metrics.


🧰 Tools That Help

  • AWS SAM (Serverless Application Model)

  • Serverless Framework

  • Zappa (for Flask/Django apps)

Comments

Popular posts from this blog

How to Repurpose Old Content for Better Engagement

Introduction to AWS for Data Science Beginners

Why Learn Full Stack Java?