Skip to content

Compute WritingCode Python

Braden Hitchcock edited this page Jan 30, 2020 · 4 revisions

Writing Code for the Python Runtime

The Scootr AWS Driver uses AWS Lambda to deploy compute resources to the cloud. As such, the code you write will need to conform to the API specified by the AWS Lambda services. Generally speaking, how you write your handler will depend on the event triggering your handler and on any resource references you may be using. However, most handlers written in Python will adhere to the following format (assuming Python 3):

def endpoint(event, context):
    # Business logic for handling the event goes here.
    #
    # You can optionally return a value that will be handled depending on
    # the type of event that triggered the lambda function.
    print("Hello, world!")

IMPORTANT: For use with the Scootr AWS driver, you must have a method definition called endpoint in your code that will serve as the entry point for the HTTP request event.

NOTE: The use of stdout or stderr inside the handler will log the provided arguments to the lambda functions CloudWatch Log Group.

Handling HTTP Events

The most common type of event used to trigger a compute resource in Scootr is the HTTP event. In AWS, this event maps to an API Gateway endpoint.

The Request

The Python dictionary below is a simplified example of what the event parameter might look. The example assumes we have received a POST request to the /users/{id} endpoint (where the value of 123 is used as the id URL path parameter):

event = {
    "httpMethod": "POST",
    "path": "/users/123",

    # Parameters from the URL. They will be strings.
    "pathParameters": {
        "id": "123"
    },

    # Empty in this case, but normally they will be strings.
    "queryStringParameters": {},

    # The raw request body. If the Content-Type of the request is
    # 'application/json', this would be a JSON formatted string.
    "body": "",

    # Key-value pairs of HTTP headers.
    "headers": { ... },
}

To learn more about these and other properties on the event parameter passed to the handler function, see the documentation for using AWS Lambda with API Gateway.

The Response

When responding to an API Gateway event, you will use the following general response format:

import json

def endpoint(event, context):
    # Do something with the event here. Then, return a result
    # that will get sent as the HTTP response to the request.
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": json.dumps({ "message": "Hello, world!" })
    }

For more information about the response object, see the response format for API Gateway Lambda integrations.

A Note About DRY Code and The AWS Response Format

It can be helpful to create a function that will create an HTTP response object that adheres to AWS Lambda's API that you can reuse in your handler depending on the type of response you need to send. Here is an example of how such a helper could be implemented:

def create_json_response(status_code, body = {}, headers = {}):
    headers_to_send = {
        "Content-Type": "application/json"
    }
    headers_to_send.update(headers)
    return {
        "statusCode": status_code,
        "headers": headers_to_send,
        "body": json.dumps(body)
    }

You could then use the create_json_response method as follows in your handler:

def endpoint(event, context):
    try:
        response = some_asynchronous_computation_that_could_fail()
        return create_json_resopnse(200, { "message": "Success", "data": response })
    except Exception as e:
        return create_json_response(500, { "message": "Failure", "details": str(e) })

What's Next?

Check out the AWS SDKs for Python by visiting the supported runtimes page.