AWS API GW + Lambda Flask

Viewed 1356

I am trying to get an app set up with API Gateway and Lambda with Flask. When I use a simple lambda function to return a string everything works fine.

def lambda_handler(event, context):
    return "Hello world" 

However when I try and run this same thing through flask-lambda I get an error with this code:

from flask_lambda import FlaskLambda

app = FlaskLambda(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    return "Hello world" 


if __name__ == '__main__':
    app.run(debug=True)

Here is the error I get through the browser:

{"errorMessage": "'wsgi.url_scheme'", "errorType": "KeyError", "stackTrace": ["  File \"/var/task/flask_lambda.py\", line 97, in __call__\n    return super(FlaskLambda, self).__call__(event, context)\n", "  File \"/var/task/flask/app.py\", line 2088, in __call__\n    return self.wsgi_app(environ, start_response)\n", "  File \"/var/task/flask/app.py\", line 2065, in wsgi_app\n    ctx = self.request_context(environ)\n", "  File \"/var/task/flask/app.py\", line 1982, in request_context\n    return RequestContext(self, environ)\n", "  File \"/var/task/flask/ctx.py\", line 309, in __init__\n    self.url_adapter = app.create_url_adapter(self.request)\n", "  File \"/var/task/flask/app.py\", line 1774, in create_url_adapter\n    return self.url_map.bind_to_environ(\n", "  File \"/var/task/werkzeug/routing.py\", line 1651, in bind_to_environ\n    wsgi_server_name = get_host(environ).lower()\n", "  File \"/var/task/werkzeug/wsgi.py\", line 113, in get_host\n    environ[\"wsgi.url_scheme\"],\n"]}

I don't know if I need to add env variables to the lambda or what. I've added the following env vars to test, just throwing stuff at the wall:

Environment:
        Variables: 
          TABLE_NAME: blah-table
          REGION_NAME: !Ref AWS::Region
          SERVER_NAME: !Sub 'xxxxxxxxx.execute-api.${AWS::Region}.amazonaws.com'
          SERVER_PORT: 443
          HTTP_HOST: !Sub 'xxxxxxxx.execute-api.${AWS::Region}.amazonaws.com'
          WSGI_SERVER_NAME: !Sub 'xxxxxxxx.execute-api.${AWS::Region}.amazonaws.com'

Any nudge in the right direction is much appreciated.

1 Answers

I've given up using flask-lambda and rather modified the awsgi https://github.com/slank/awsgi package to work with the payload version 2.0 event format.

from https://github.com/slank/awsgi:

import awsgi
from flask import (
    Flask,
    jsonify,
)

app = Flask(__name__)


@app.route('/')
def index():
    return jsonify(status=200, message='OK')


def lambda_handler(event, context):
    return awsgi.response(app, event, context, base64_content_types={"image/png"})
Related