From 44bba45c7bf83948ee65129c069f1ff7c5a9b874 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Tue, 11 Apr 2017 13:46:53 +0100 Subject: [PATCH] Add error response --- lantern/error.py | 12 ++++++++++++ lantern/handle.py | 9 ++++----- lantern/route.py | 8 ++++++-- lantern/templates/error.html | 2 ++ setup.py | 3 ++- 5 files changed, 26 insertions(+), 8 deletions(-) create mode 100644 lantern/error.py create mode 100644 lantern/templates/error.html diff --git a/lantern/error.py b/lantern/error.py new file mode 100644 index 0000000..a0594a9 --- /dev/null +++ b/lantern/error.py @@ -0,0 +1,12 @@ +from jinja2 import Template +from sanic.response import html +import os + + +TEMPLATE = os.path.join(os.path.dirname(__file__), 'templates', 'error.html') + + +def error_response(error_str): + with open(TEMPLATE) as f: + template = Template(f.read()) + return html(template.render(error=error_str), status=500) diff --git a/lantern/handle.py b/lantern/handle.py index 260bc22..0c86328 100644 --- a/lantern/handle.py +++ b/lantern/handle.py @@ -8,13 +8,12 @@ Result = namedtuple('Result', ['exit_code', 'html', 'error']) def execute_handle(executable, request_data): input_data = json.dumps(request_data).encode('utf-8') - cmd = subprocess.run(executable, input=input_data, stdout=subprocess.PIPE) + try: + cmd = subprocess.run(executable, input=input_data, stdout=subprocess.PIPE) + except Exception as e: + return Result(1, None, str(e)) return Result( cmd.returncode, cmd.stdout.decode('utf-8'), cmd.stderr.decode('utf-8') if cmd.stderr is not None else None ) - - -def get_http_status_code(exit_code): - return 200 if exit_code == 0 else 500 diff --git a/lantern/route.py b/lantern/route.py index 323b85d..3448ce5 100644 --- a/lantern/route.py +++ b/lantern/route.py @@ -1,9 +1,13 @@ from sanic.response import html -from lantern.handle import execute_handle, get_http_status_code +from lantern.handle import execute_handle +from lantern.error import error_response import os async def main_route(request, path=None): handle = os.path.join(os.path.dirname(__file__), 'test_handle.py') result = execute_handle(handle, {}) - return html(result.html, status=get_http_status_code(result.exit_code)) + if result.exit_code != 0: + return error_response(result.error) + + return html(result.html, status=200) diff --git a/lantern/templates/error.html b/lantern/templates/error.html new file mode 100644 index 0000000..2b65fba --- /dev/null +++ b/lantern/templates/error.html @@ -0,0 +1,2 @@ +

Error

+

{{ error }}

diff --git a/setup.py b/setup.py index 6d37e58..e0371f7 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,8 @@ setup( version="1.0", install_requires=[ "sanic==0.4.1", - "sanic-useragent==0.1.2" + "sanic-useragent==0.1.2", + "Jinja2==2.9.6" ], entry_points=""" [console_scripts]