forked from logandk/serverless-wsgi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsgi.py
68 lines (51 loc) · 1.91 KB
/
wsgi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module loads the WSGI application specified by FQN in `.wsgi_app` and invokes
the request when the handler is called by AWS Lambda.
Author: Logan Raarup <[email protected]>
"""
import importlib
import json
import os
import sys
# Call decompression helper from `serverless-python-requirements` if
# available. See: https://github.com/UnitedIncome/serverless-python-requirements#dealing-with-lambdas-size-limitations
try:
import unzip_requirements # noqa
except ImportError:
pass
import serverless_wsgi
def load_config():
""" Read the configuration file created during deployment
"""
root = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(root, ".wsgi_app"), "r") as f:
return json.loads(f.read())
def import_app(config):
""" Load the application WSGI handler
"""
wsgi_fqn = config["app"].rsplit(".", 1)
wsgi_fqn_parts = wsgi_fqn[0].rsplit("/", 1)
if len(wsgi_fqn_parts) == 2:
root = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(root, wsgi_fqn_parts[0]))
wsgi_module = importlib.import_module(wsgi_fqn_parts[-1])
return getattr(wsgi_module, wsgi_fqn[1])
def append_text_mime_types(config):
""" Append additional text (non-base64) mime types from configuration file
"""
if "text_mime_types" in config and isinstance(config["text_mime_types"], list):
serverless_wsgi.TEXT_MIME_TYPES.extend(config["text_mime_types"])
def make_handler(wsgi_app):
""" Factory that builds a Lambda event handler for a given WSGI application
"""
return lambda event, context: serverless_wsgi.handle_request(
wsgi_app, event, context
)
# Read configuration and import the WSGI application
config = load_config()
wsgi_app = import_app(config)
append_text_mime_types(config)
# Declare the AWS Lambda event handler
handler = make_handler(wsgi_app)