Serverless WSGI

3.1.0 · active · verified Sat Apr 11

Serverless WSGI is a Python library and Serverless Framework plugin that enables the deployment of standard Python WSGI applications (like Flask, Django, Pyramid) to AWS Lambda, using API Gateway as the HTTP frontend. It transparently converts API Gateway requests to WSGI requests and vice-versa, handling packaging and deployment complexities. The current version is 3.1.0, and it is actively maintained with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `serverless-wsgi` with a simple Flask application for direct use within an AWS Lambda function. The `lambda_handler` function serves as the entry point, passing the AWS event and context to `serverless_wsgi.handle_request`. For actual deployment, the `serverless-wsgi` plugin for the Serverless Framework is typically used, which abstracts away the manual `lambda_handler` setup by configuring `wsgi_handler.handler` in your `serverless.yml`.

import os
import serverless_wsgi
from flask import Flask, jsonify

# Your Flask (or any WSGI) application
app = Flask(__name__)

@app.route('/')
def hello():
    return jsonify(message='Hello from Serverless WSGI!')

@app.route('/env')
def show_env():
    return jsonify(environment=dict(os.environ))

# The AWS Lambda handler function
def lambda_handler(event, context):
    # This is the core function from the serverless-wsgi Python library
    # that maps API Gateway events to your WSGI application.
    return serverless_wsgi.handle_request(app, event, context)

# Example of how you would run it locally (for testing)
if __name__ == '__main__':
    # In a real setup, this is handled by `sls wsgi serve` or a WSGI server.
    # For a minimal local test, you could use Werkzeug's run_simple.
    from werkzeug.serving import run_simple
    print("Running local Flask app on http://127.0.0.1:5000/")
    run_simple('127.0.0.1', 5000, app, use_reloader=True, use_debugger=True)

view raw JSON →