Search code examples
pythonaws-lambdapackagemiddleware

How to use pymiddy on Lambda with python?


The pymiddy package for AWS Lambda with Python seems to lack a clear example, or I'm having a difficult time figuring it out. How do I use the middleware on Lambda? Package: https://pypi.org/project/pymiddy/

The code I have so far is

from pymiddy import Middy

@Middy
def handler(event, context):
    ...rest of the handler method

From the package's example, do I now have to create the "MyCustomMiddleware" class, or can I already an already defined .before method to execute code before the handler() method?

For example, at the bottom of the lambda, I added

class MyCustomMiddleware(object):
    def before(self, state):
        print("Got to before step")

    def after(self, state):
        pass

    def error(self, state):
        pass

however the before step is not yet being reached. How can I have the .before middleware run before the handler()?


Solution

  • Finally figured it out.

    from pymiddy import Middy
    
    @Middy
    def handler(event, context):
         print('Running lambda')
    #    raise ValueError('got exception') # If exception is to be thrown
    
    
    class MyCustomMiddleware(object):
         def before(self, state):
              print("Running before")
    
         def after(self, state):
              print("Running after")
    
         def error(self, state):
              print('Found an exception...')
              print(state['exception'])
        
    handler.use(MyCustomMiddleware())
    

    As shown in the last line, the method (handler in this case), has to "register" the custom middleware with the .use() call. Then the before, after, and error middlewares will run at appropriate times.

    Running the above code gave the output:

    Running before
    Running lambda
    Running after
    

    If the raise ValueError is uncommented, the following is output instead:

    Running before
    Running lambda
    Found an exception...
    got exception