DEV Community

Rey Abolofia for AWS Community Builders

Posted on

1

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

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Best Practices for Running  Container WordPress on AWS (ECS, EFS, RDS, ELB) using CDK cover image

Best Practices for Running Container WordPress on AWS (ECS, EFS, RDS, ELB) using CDK

This post discusses the process of migrating a growing WordPress eShop business to AWS using AWS CDK for an easily scalable, high availability architecture. The detailed structure encompasses several pillars: Compute, Storage, Database, Cache, CDN, DNS, Security, and Backup.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay