Pyjo.Server.Lambda - AWS Lambda server

from Pyjo.Server.Lambda import Lambda

server = Lambda()


@server.unsubscribe('request').on('request')
def request(server, tx):
    # Request
    method = tx.req.method
    path = tx.req.url.path

    # Response
    tx.res.code = 200
    tx.res.headers.content_type = 'text/plain'
    tx.res.body = f'{method} request for {path}!'.encode()

    # Resume transaction
    tx.resume()


handler = server.to_lambda_app()

# Or import the module, as in Google Python Style Guide

import Pyjo.Server.Lambda

server = Pyjo.Server.Lambda.new()


@server.unsubscribe('request').on('request')
def request(server, tx):
    # Request
    method = tx.req.method
    path = tx.req.url.path

    # Response
    tx.res.code = 200
    tx.res.headers.content_type = 'text/plain'
    tx.res.body = f'{method} request for {path}!'.encode()

    # Resume transaction
    tx.resume()


handler = server.to_lambda_app()

Pyjo.Server.Lambda allows Pyjoyment applications to run as event functions of AWS Lambda, whose handler gets the event of an HTTP request and returns its response, with the payload formats of API Gateway, of Function URLs and of Application Load Balancers:

  • the format 2.0 of HTTP APIs and Function URLs, whose cookies are the Cookie header of the request and the Set-Cookie headers of the response, and whose stage, other than $default, is the base path of the URL;

  • the format 1.0 of REST APIs, whose stage is the base path of the URL, and whose decoded parameters of the query are encoded again;

  • the events of Application Load Balancers, whose parameters of the query are as they were sent, with the headers of multiple values when the target group has them, and only the last value of a header otherwise.

The event and the context of the invocation are lambda.event and lambda.context of env of the request. A body that the event has in Base64 is decoded, and the body of a response is Base64 too, unless its content type is text, JSON, XML, JavaScript or YAML that is UTF-8. The handler is synchronous, so the event loop of Pyjo.IOLoop runs until the response is complete, which can come later and in chunks, whose framing is left out, as the response of an event function is the whole body.

# The handler "myapp.handler" of an event function
handler = Pyjo.Server.Lambda.new(app=app).to_lambda_app()

With the invoke mode RESPONSE_STREAM of invoke_mode, which follows the one of the Function URL or the response transfer mode of the REST API of API Gateway, the handler returns an iterator of the body as it is written instead, which the runtime client below streams: the status and the headers as JSON, 8 null bytes, and the chunks of the body as they come, with the content type application/vnd.awslambda.http-integration-response of the iterator. The events of Application Load Balancers, which have no streaming, get the whole response.

# PYJO_LAMBDA_INVOKE_MODE=RESPONSE_STREAM in the environment of the function
handler = Pyjo.Server.Lambda.new(app=app).to_lambda_app()

Events

Pyjo.Server.Lambda inherits all events from Pyjo.Server.

Attributes

Pyjo.Server.Lambda inherits all attributes from Pyjo.Server and implements invoke_mode.

Runtime client

Usage: python -m Pyjo.Server.Lambda [OPTIONS] [HANDLER]

  python -m Pyjo.Server.Lambda myapp.handler
  AWS_LAMBDA_RUNTIME_API=127.0.0.1:9001 python -m Pyjo.Server.Lambda myapp.handler

Options:
  -h, --help   Show this message

The client of the Runtime API of AWS Lambda, which runs the handler of an event function, module.function or the one of _HANDLER, as a custom runtime does: it gets the next invocation from the API of AWS_LAMBDA_RUNTIME_API, calls the handler with its event and a context, and posts the value that the handler returns as JSON, or its exception, one invocation after another. An iterator of bytes that the handler returns is a streaming response, chunked as it is iterated, of the content_type of the iterator or application/octet-stream, with an exception in the middle of it in the trailers of the error, as the Runtime API takes it, and an exception before its first chunk as the error of the invocation. An exception of the import of the handler is an error of the initialization, which ends the client. The handler can be any handler of an event function, also one of another framework, which runs an event loop of its own, as the client runs outside of the event loop of Pyjo.IOLoop, and the directory of the handler, LAMBDA_TASK_ROOT or the current one, is the first one of sys.path.

#!/bin/sh
# The bootstrap of a custom runtime, as provided.al2023
exec python3 -m Pyjo.Server.Lambda

The context has the attributes and the method of the context of the Python runtime of Lambda: aws_request_id, invoked_function_arn, function_name, function_version, memory_limit_in_mb, log_group_name, log_stream_name, identity, client_context and get_remaining_time_in_millis(), from the headers of the invocation and the variables of the environment that Lambda sets.

See also

Pyjoyment.Command.lambda, Pyjo.Server.WSGI, Pyjoyment, https://mojolicious.org.

Classes

class Pyjo.Server.Lambda.Pyjo_Server_Lambda(*, invoke_mode: str | None = None, **kwargs: Any)[source]

Pyjo.Server.Lambda inherits all attributes and methods from Pyjo.Server and implements the following new ones.

property invoke_mode: str[source]
mode = server.invoke_mode
server.invoke_mode = 'RESPONSE_STREAM'

The mode of the invocations, as the InvokeMode of the Function URL, or the response transfer mode of API Gateway, of the function, which the function does not learn from its invocations: BUFFERED or RESPONSE_STREAM, defaults to the value of the PYJO_LAMBDA_INVOKE_MODE environment variable or BUFFERED.

run(event: Event, context: Any = None) → Response | Iterator[bytes][source]
response = server.run(event, context)

Run the event of an HTTP request and return its response, or the iterator of a streaming response with the invoke mode RESPONSE_STREAM.

run_runtime() → None[source]
server.run_runtime()

Run the application for the invocations of the Runtime API of AWS_LAMBDA_RUNTIME_API, one after another, as the runtime client does with a handler, until the process ends, so that the script of the application is the runtime of a custom runtime itself.

to_lambda_app() → Handler[source]
handler = server.to_lambda_app()

Turn Pyjoyment application into the handler of an event function of AWS Lambda.

Pyjo.Server.Lambda.main(argv: Sequence[str] | None = None) → NoReturn[source]
main(['myapp.handler'])

The command line interface of the runtime client: parse the options and run the handler for the invocations of the Runtime API.