argh 2 days trying to work python3 into working python2 :(

This commit is contained in:
rocky4570fft 2016-10-10 01:13:52 +10:00
commit dc98cf6f64
3 changed files with 78 additions and 36 deletions

View file

@ -42,7 +42,12 @@ class LambdaFunction(object):
self.version = '$LATEST'
self.last_modified = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
if 'ZipFile' in self.code:
to_unzip_code = base64.b64decode(self.code['ZipFile'])
# more hackery to handle unicode/bytes/str in python3 and python2 - argh!
try:
to_unzip_code = base64.b64decode(bytes(self.code['ZipFile'], 'utf-8'))
except Exception:
to_unzip_code = base64.b64decode(self.code['ZipFile'])
zbuffer = io.BytesIO()
zbuffer.write(to_unzip_code)
zip_file = zipfile.ZipFile(zbuffer, 'r', zipfile.ZIP_DEFLATED)
@ -105,10 +110,28 @@ class LambdaFunction(object):
"Configuration": self.get_configuration(),
}
def convert(self, s):
try:
return str(s, encoding='utf8')
except:
return s
def is_json(self, test_str):
try:
response = json.loads(test_str)
except:
response = test_str
return response
def _invoke_lambda(self, code, event={}, context={}):
# TO DO: context not yet implemented
mycode = "\n".join([self.code, 'print(lambda_handler(%s, %s))' % (event, context)])
print("moto_lambda_debug: ", mycode)
try:
mycode = "\n".join(['import json',
self.convert(self.code),
self.convert('print(lambda_handler(%s, %s))' % (self.is_json(self.convert(event)), context))])
print("moto_lambda_debug: ", mycode)
except Exception as ex:
print('fuck ', ex)
try:
codeOut = StringIO()
@ -118,35 +141,25 @@ class LambdaFunction(object):
exec(mycode)
exec_err = codeErr.getvalue()
exec_out = codeOut.getvalue()
result = "\n".join([exec_out, exec_err])
result = "\n".join([exec_out, self.convert(exec_err)])
except Exception as ex:
result = '%s\n\n\nException %s, %s' % (mycode, ex, ex.message)
result = '%s\n\n\nException %s' % (mycode, ex)
finally:
codeErr.close()
codeOut.close()
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
return result
def is_json(self, test_str):
try:
response = json.loads(test_str)
except:
response = test_str
return response
return self.convert(result)
def invoke(self, request, headers):
payload = dict()
# Get the invocation type:
invoke_type = request.headers.get("x-amz-invocation-type")
response = self._invoke_lambda(code=self.code, event=self.is_json(request.body))
r = self._invoke_lambda(code=self.code, event=request.body)
if request.headers.get("x-amz-invocation-type") == "RequestResponse":
encoded = base64.b64encode(response.encode('utf-8'))
payload['result'] = encoded
encoded = base64.b64encode(r.encode('utf-8'))
headers["x-amz-log-result"] = encoded.decode('utf-8')
elif request.headers.get("x-amz-invocation-type") == "Event":
payload['result'] = 'good' # nothing should be sent back possibly headers etc.
payload['result'] = headers["x-amz-log-result"]
return json.dumps(payload, indent=4)