DEV Community

Rey Abolofia for AWS Community Builders

Posted on

Serverless wsgi zipped packages

I just spent the longest time trying to debug why my Flask app run on AWS Lambda wasn't working correctly. Consistently, I was seeing the error,

No module named 'wsgi_handler'
Enter fullscreen mode Exit fullscreen mode

I was able to track this down to how I am packaging my function. I create a zip file containing my function code and its requirements. Using Serverless Framework, this looks like,

package:
  artifact: .package/package.zip
Enter fullscreen mode Exit fullscreen mode

I was then using the plugin serverless-wsgi to serve my Flask app.

The problem was that the serverless-wsgi plugin was unable to include its required wsgi_handler code file. This is because my code was already zipped before running serverless deploy.

The solution was to remove the serverless-wsgi plugin and wrap the handler manually.

  1. Install serverless-wsgi as a python dependency
  $ pip install serverless-wsgi
  $ pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode
  1. Create the lambda handler
  # file handlers/ui_handler/__init__.py

  import serverless_wsgi

  from handlers.ui_handler.app import app

  def handle(event, context):
      return serverless_wsgi.handle_request(app, event, context)
Enter fullscreen mode Exit fullscreen mode
  1. Using Serverless Framework, set the handler to this function
  functions:
    ui:
      handler: handlers/ui_handler.handle
      url: true
Enter fullscreen mode Exit fullscreen mode

Top comments (0)