Last active
October 23, 2023 20:30
-
-
Save benkehoe/efb75a793f11d071b36fed155f017c8f to your computer and use it in GitHub Desktop.
Code pattern for implementing class-based AWS Lambda handlers in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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
Anybody else read this: Skip the below, it does not seem to work. The base pattern works well.
@LambdaHandler
class MyLambdaClass(LambdaBase):
def init(self, ...): # implementation-specific args and/or kwargs
# implementation
def LambdaHandler(func):
# Creates dynamic handler in caller's module called MyCallingClassHandler