From ef00f191f3f2a2672449faa70d4f67a477e9abf2 Mon Sep 17 00:00:00 2001 From: Johan Pauwels Date: Thu, 28 May 2020 19:14:08 +0100 Subject: [PATCH 1/2] Handle non-string payloads and respect encoding for string payloads Signed-off-by: Johan Pauwels --- template/python3/index.py | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/template/python3/index.py b/template/python3/index.py index 6e1a22f8..c477224e 100644 --- a/template/python3/index.py +++ b/template/python3/index.py @@ -3,19 +3,30 @@ # Licensed under the MIT license. See LICENSE file in the project root for full license information. import sys +import os +import json +from cgi import parse_header from function import handler -def get_stdin(): - buf = "" - while(True): - line = sys.stdin.readline() - buf += line - if line == "": - break - return buf - if __name__ == "__main__": - st = get_stdin() + st = sys.stdin.buffer.read() + # decode text to string + content_type, type_options = parse_header(os.getenv('Http_Content_Type', '')) + if not content_type or content_type.startswith('text/') or content_type == 'application/x-www-form-urlencoded': + encoding = type_options.get('charset', 'utf-8') + try: + st = st.decode(encoding) + except UnicodeDecodeError: + # if explicitly defined encoding can't decode bytes, fail + if 'charset' in type_options: + raise + # otherwise utf-8 was incorrect guess, then keep as bytes + # unknown encoding (LookupError) will fail and propagate + # decode JSON and JSON-LD to dictionary + elif content_type.endswith('json'): + st = json.load(st) + # otherwise keep bytes + ret = handler.handle(st) if ret != None: print(ret) From 8fad78fc1d92c92f6b893a3e4b706a02a92562bd Mon Sep 17 00:00:00 2001 From: Johan Pauwels Date: Thu, 28 May 2020 19:35:09 +0100 Subject: [PATCH 2/2] Encode response to JSON if necessary Signed-off-by: Johan Pauwels --- template/python3/index.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/template/python3/index.py b/template/python3/index.py index c477224e..4c894542 100644 --- a/template/python3/index.py +++ b/template/python3/index.py @@ -28,5 +28,12 @@ # otherwise keep bytes ret = handler.handle(st) - if ret != None: - print(ret) + + # encode response to JSON if necessary + if ret is not None: + if isinstance(ret, bytes): + sys.stdout.buffer.write(ret) + elif isinstance(ret, str): + sys.stdout.write(ret) + else: + json.dump(ret, sys.stdout)