Zappa Documentation

repository·master·Indexed 25 days ago

https://github.com/zappa/zappa

A deployment tool for serverless Python applications on AWS. Zappa automates packaging and deploying WSGI and ASGI web apps (such as Django, Flask, FastAPI, and Starlette) to AWS Lambda and API Gateway. It supports infinite scaling, cost-efficient hosting, Docker image deployments via Amazon ECR, and event-driven triggers from AWS services including S3, SNS, DynamoDB, Kinesis, SQS, and Lex Bots.

Tokens
13.7K
Snippets
43
Records
93
Agent score
87%

What's inside Zappa

  1. Overview of Zappa

    master

    Zappa is a tool for building and deploying serverless, event-driven Python applications on AWS Lambda and API Gateway. It supports both WSGI and ASGI frameworks.

    Key features include:

    • Infinite Scaling: AWS handles horizontal scaling automatically.
    • Zero Maintenance: No permanent infrastructure to manage.
    • Cost Efficiency: You only pay for the milliseconds of execution time used.
    • Hybrid Capabilities: Supports SSL certificates, global deployment, API access management, and automatic security policy generation.
  2. Quickstart: Deploy a Python web app with Zappa

    master

    Zappa allows you to deploy WSGI and ASGI Python applications (such as Django, Flask, FastAPI, and Starlette) to AWS Lambda and API Gateway. To get started with a minimal deployment, follow these steps:

    1. Install Zappa via pip.
    2. Initialize your Zappa configuration.
    3. Deploy your application.

    This process handles the infrastructure setup, allowing for infinite scaling and zero maintenance.

    $ pip install zappa
    $ zappa init
    $ zappa deploy
  3. Install Let's Encrypt certificate in AWS API Gateway

    master

    Once your certificate is generated in /etc/letsencrypt/live/yoursub.example.com/, use the following mapping to configure a Custom Domain Name in the AWS API Gateway console:

    AWS API Gateway Custom Domain Name Setting fieldFile/Value to use
    Domain nameyoursub.example.com
    Certificate nameyoursub.example.com
    Certificate private keyprivkey.pem
    Certificate bodycert.pem
    Certificate chainfullchain.pem (Note: Only copy the 2nd part of the chain; the 1st part is the Certificate body already provided)

    After saving, update your domain's DNS CNAME to point to the API Gateway domain. Remember that these certificates expire every 90 days and must be re-generated.

  4. Implement WebSocket support

    master

    Zappa supports API Gateway WebSocket APIs. It auto-detects WebSocket usage if you import from zappa.websocket.

    Using Decorators: Use @on_connect, @on_disconnect, and @on_message to handle events.

    Sending Messages: Use send_message(connection_id, data) where data can be a dict (JSON), str (UTF-8), or bytes (raw binary).

    Manual Handler Configuration: If auto-detection fails, specify the module path using websocket_handler_module in your settings.

    from zappa.websocket import on_connect, on_disconnect, on_message, send_message
    
    @on_message
    def handle_message(event, context):
        connection_id = event["requestContext"]["connectionId"]
        send_message(connection_id, {"echo": "data"})
        return {"statusCode": 200}
  5. Install Zappa from a local repository

    master

    If you want to use the current git HEAD of the Zappa repository, pip install -e . may not work. Instead, clone the repository to your machine and use one of the following methods:

    1. Install directly via path: pip install /path/to/zappa/repo
    2. Create a symbolic link in your local project: ln -s /path/to/zappa/repo/zappa zappa
  6. Enable Bash completion for Zappa CLI

    master

    To enable bash completion, add the following to your .bashrc:

    eval "$(register-python-argcomplete zappa)"

    Note: register-python-argcomplete is provided by the argcomplete package. If installed in a virtualenv, the command must be run within that environment. Alternatively, you can use activate-global-python-argcomplete --dest=- > file and source the resulting file in your .bashrc.

    eval "$(register-python-argcomplete zappa)"
  7. Handle exceptions in asynchronous tasks

    master

    When using @task, avoid returning a non-empty value inside an except block. Because AWS Lambda may retry on errors, returning a value like a Response object inside an exception handler can cause side effects (like sending duplicate emails). To ensure the fault handler executes only once, return an empty dictionary {} or True in the except block.

    @task
    def make_pie():
        try:
            """code block""
        except Fault as error:
            """send an email"""
        ...
        return {} #or return True
  8. Install tools for Let's Encrypt HTTP validation

    master

    To use Let's Encrypt with HTTP validation for a Zappa website on an API Gateway Custom Domain, you need to install the Let's Encrypt client and localtunnel.

    1. Clone the Let's Encrypt repository:
    $ git clone https://github.com/letsencrypt/letsencrypt
    $ cd letsencrypt
    1. Install localtunnel globally via npm:
    $ npm install -g localtunnel
    # Install Let's Encrypt via git
    $ git clone https://github.com/letsencrypt/letsencrypt
    $ cd letsencrypt
    
    # Install localtunnel via npm
    $ npm install -g localtunnel
  9. Schedule a function packaged with a WSGI app

    master
    If a function is part of your main WSGI application deployment, you can schedule it using the environment name. For example, if your production environment is named prod, you can schedule a function defined in your code.
  10. Execute functions in response to AWS events

    master

    You can configure Zappa to trigger Python functions in response to AWS ecosystem events (S3, SNS, DynamoDB, Kinesis, SQS, etc.).

    In your _zappa_settings.json file, define an events array within your environment configuration. Each event object must specify the function (the full path to your Python function) and an event_source containing the AWS resource arn.

    Note: The target function must accept event and context parameters. To apply these event configurations, run the zappa schedule <environment> command.

    $ zappa schedule production
  11. Deploy using Docker images

    master

    Zappa supports deploying and updating Lambda functions using images from Amazon ECR. When using --docker-image-uri, the image is responsible for the application code and runtime.

    Important: Do NOT use slim_handler with Docker deployments. The runtime setting is also ignored as it is determined by the image.

    To bypass Python version checks when using a custom runtime image, set the environment variable ZAPPA_RUNNING_IN_DOCKER=True in your shell or Dockerfile.