forked from sivel/flask-lambda
- Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathflask_lambda.py
More file actions
Latest commit
123 lines (95 loc) · 3.68 KB
/
Copy pathflask_lambda.py
File metadata and controls
123 lines (95 loc) · 3.68 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# -*- coding: utf-8 -*-
# Copyright 2016 Matt Martz
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
importsys
fromioimportStringIO
fromurllib.parseimporturlencode
fromflaskimportFlask
try: # werkzeug <= 2.0.3
fromwerkzeug.wrappersimportBaseRequest
except: # werkzeug > 2.1
fromwerkzeug.wrappersimportRequestasBaseRequest
__version__='0.0.4'
defmake_environ(event):
environ= {}
print('event', event)
# key might be there but set to None
headers=event.get('headers', {}) or {}
forhdr_name, hdr_valueinheaders.items():
hdr_name=hdr_name.replace('-', '_').upper()
ifhdr_namein ['CONTENT_TYPE', 'CONTENT_LENGTH']:
environ[hdr_name] =hdr_value
continue
http_hdr_name='HTTP_{}'.format(hdr_name)
environ[http_hdr_name] =hdr_value
qs=event['queryStringParameters']
environ['REQUEST_METHOD'] =event['httpMethod']
environ['PATH_INFO'] =event['path']
environ['QUERY_STRING'] =urlencode(qs) ifqselse''
environ['REMOTE_ADDR'] =environ.get('X_FORWARDED_FOR')
environ['HOST'] ='{}:{}'.format(
environ.get('HTTP_HOST', ''),
environ.get('HTTP_X_FORWARDED_PORT', ''),
)
environ['SCRIPT_NAME'] =''
environ['SERVER_NAME'] ='SERVER_NAME'
environ['SERVER_PORT'] =environ.get('HTTP_X_FORWARDED_PORT', '')
environ['SERVER_PROTOCOL'] ='HTTP/1.1'
environ['CONTENT_LENGTH'] =str(
len(event['body']) ifevent['body'] else''
)
environ['wsgi.url_scheme'] =environ.get('HTTP_X_FORWARDED_PROTO')
environ['wsgi.input'] =StringIO(event['body'] or'')
environ['wsgi.version'] = (1, 0)
environ['wsgi.errors'] =sys.stderr
environ['wsgi.multithread'] =False
environ['wsgi.run_once'] =True
environ['wsgi.multiprocess'] =False
BaseRequest(environ)
returnenviron
classLambdaResponse(object):
def__init__(self):
self.status=None
self.response_headers=None
defstart_response(self, status, response_headers, exc_info=None):
self.status=int(status[:3])
self.response_headers=dict(response_headers)
classFlaskLambda(Flask):
def__call__(self, event, context):
try:
if'httpMethod'notinevent:
print('call as flask app')
# In this "context" `event` is `environ` and
# `context` is `start_response`, meaning the request didn't
# occur via API Gateway and Lambda
returnsuper(FlaskLambda, self).__call__(event, context)
print('call as aws lambda')
response=LambdaResponse()
body=next(self.wsgi_app(
make_environ(event),
response.start_response
))
return {
'statusCode': response.status,
'headers': response.response_headers,
'body': body.decode('utf-8')
}
exceptExceptionase:
print('unexpected error', e)
return {
'statusCode': 500,
'headers': {},
'body': 'internal server error'
}