Skip to content

Instantly share code, notes, and snippets.

@superposition
Forked from benkehoe/LambdaBase.py
Created April 17, 2018 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superposition/d7951389efa65a55bc02fa068ed61352 to your computer and use it in GitHub Desktop.
Save superposition/d7951389efa65a55bc02fa068ed61352 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