AWS Chalice

repository·master·Indexed 27 days ago

https://github.com/aws/chalice

A Python framework for writing serverless applications that simplifies creating, deploying, and managing AWS Lambda-based applications. It features a decorator-based API for AWS services, automatic IAM policy generation, and support for various event sources including S3, SNS, SQS, Kinesis, and DynamoDB. The framework includes tools for handling HTTP errors via ChaliceViewError, configuring CORS, managing WebSockets, and organizing large applications using Blueprints.

Tokens
46.5K
Snippets
155
Records
251
Agent score
94%

What's inside aws-chalice

  1. Understand AWS Chalice core components

    master

    AWS Chalice is a framework for writing serverless applications in Python. It consists of three primary components:

    1. A CLI: For managing project lifecycle tasks like creation and deployment.
    2. A declarative Python API: Used to connect AWS event sources to Lambda functions.
    3. A runtime component: Provides APIs that are accessible within your Lambda functions.

    Chalice is designed to handle boilerplate and low-level serverless details, allowing you to focus on business logic while providing deep integration with various AWS services.

  2. Media Query Application Architecture

    master

    The Media Query application is an image/video processing pipeline using multiple event handlers:

    • handle_object_created: Triggered by S3 uploads. Processes images via Rekognition DetectLabels or starts asynchronous video analysis via Rekognition StartLabelDetection.
    • handle_object_deleted: Triggered by S3 deletions to remove entries from DynamoDB.
    • add_video_labels: Triggered by SNS notifications when asynchronous video analysis is complete. Uses Rekognition GetLabelDetection to retrieve and store results.
    • api_handler: Triggered by HTTP requests via API Gateway to query the DynamoDB table.
  3. Compare AWS Chalice with AWS SAM and AWS CDK

    master

    Chalice is designed to work alongside AWS SAM rather than replacing it.

    • AWS SAM: Focuses on provisioning the infrastructure resources required for your application.
    • AWS Chalice: Focuses on the application code itself, providing a routing layer for REST and WebSocket APIs and decorators to connect AWS event sources to Lambda functions.
    • Integration: Chalice can integrate with AWS SAM by offloading the deployment process to AWS CloudFormation.
  4. Install and set up Chalice

    master

    To create a new Chalice project, ensure you have Python installed, create a virtual environment, install the chalice package via pip, and then use the chalice new-project command.

    $ python3 -m venv .venv
    $ . .venv/bin/activate
    $ python3 -m pip install chalice
    $ chalice new-project chalice-sns-demo
    $ cd chalice-sns-demo
  5. Capture URL path parameters

    master

    You can capture parts of a URL by using curly braces {} in the route path. These captured values are passed to your view function as keyword arguments. The argument names in your Python function must exactly match the names used within the curly braces in the route definition.

    Allowed characters in route paths are [a-zA-Z0-9._-] and curly braces.

    from chalice import Chalice
    
    app = Chalice(app_name='helloworld')
    
    @app.route('/users/{name}')
    def users(name):
        return {'name': name}
    
    @app.route('/a/{first}/b/{second}')
    def users(first, second):
        return {'first': first, 'second': second}
  6. Define View Functions with @app.route()

    master

    A view function is a Python function attached to a route using the @app.route() decorator. The function's parameters must match the number of captured URL parameters defined in the route string.

    from chalice import Chalice
    
    app = Chalice(app_name='helloworld')
    
    @app.route('/cities/{city}')
    def index(city):
        return {'city': city}
  7. Handle errors in middleware

    master

    For most event types (except REST APIs), middleware can catch exceptions raised by Lambda handlers by wrapping the get_response(event) call in a try/except block.

    Note for REST APIs: REST API view functions (@app.route) automatically catch exceptions and convert them into Response objects for backwards compatibility. Consequently, middleware for REST APIs will see a Response object returned from get_response(event) rather than a raised exception. To force an exception to propagate to middleware in a REST API, you must raise chalice.ChaliceUnhandledError.

    from chalice import Chalice, ChaliceUnhandledError, Response
    
    @app.middleware('all')
    def handle_errors(event, get_response):
        try:
            return get_response(event)
        except ChaliceUnhandledError as e:
            # This catches exceptions explicitly raised as ChaliceUnhandledError in REST APIs
            return Response(status_code=500, body=str(e),
                            headers={'Content-Type': 'text/plain'})
    
    @app.route('/error')
    def unhandled_error():
        # This will be seen by the middleware above
        raise ChaliceUnhandledError("Raising an error.")
  8. Implement Data Storage with DynamoDB or In-Memory

    master

    In the Todo application sample, data storage is abstracted via a TodoDB interface. You can use two different implementations depending on your environment:

    1. InMemoryTodoDB: An in-memory implementation used for local development and testing with chalice local. It stores data within the process and does not require an actual DynamoDB service.
    2. DynamoDBTodo: A production-ready implementation that communicates with AWS DynamoDB using boto3. It uses the APP_TABLE_NAME environment variable (configured in .chalice/config.json) to identify the target table.

    Routes should delegate data operations to these storage objects rather than containing heavy business logic.

  9. Install Chalice with CDK v2 support

    master

    To use the integration between Chalice and the AWS Cloud Development Kit (CDK), you must install the chalice[cdkv2] extra. This tutorial assumes you have Python 3.6+ and the AWS CDK (version 2) already installed via npm.

    First, install the CDK globally:

    $ npm install -g aws-cdk

    Then, install Chalice with the necessary CDK dependencies in your Python virtual environment:

    $ python3 -m pip install "chalice[cdkv2]"
    $ npm install -g aws-cdk
    $ python3 -m pip install "chalice[cdkv2]"
  10. Deploy a Chalice application

    master

    Once your application code is written in app.py, run chalice deploy from your project directory. Chalice will automatically create the necessary IAM roles, Lambda functions, and API Gateway resources.

    $ chalice deploy