Skip to content

Instantly share code, notes, and snippets.

@pablo-epl
Forked from benkehoe/LambdaBase.py
Created February 24, 2021 05:37
Show Gist options
  • Save pablo-epl/03468ee595f2dbc6ae8085b545ce317a to your computer and use it in GitHub Desktop.
Save pablo-epl/03468ee595f2dbc6ae8085b545ce317a to your computer and use it in GitHub Desktop.
Code pattern for implementing class-based AWS Lambda handlers in Python
"""Base class for implementing Lambda handlers as classes.
Used across multiple Lambda functions (included in each zip file).
Add additional features here common to all your Lambdas, like logging."""
class LambdaBase(object):
@classmethod
def get_handler(cls, *args, **kwargs):
def handler(event, context):
return cls(*args, **kwargs).handle(event, context)
return handler
def handle(self, event, context):
raise NotImplementedError
"""Implementation of a Lambda handler as a class for a specific Lambda function.
The Lambda function is deployed with handler set to MyLambdaClass.handler.
Class fields will persist across invocations for a given Lambda container,
and so are a good way to implement caching.
An instance of the class is created for each invocation, so instance fields can
be set from the input without the data persisting."""
from LambdaBase import LambdaBase
class MyLambdaClass(LambdaBase):
def __init__(self, ...): # implementation-specific args and/or kwargs
# implementation
def handle(self, event, context):
# implementation
handler = MyLambdaClass.get_handler(...) # input values for args and/or kwargs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment