Archived
1
Fork 0

Add error response

This commit is contained in:
Jake Howard 2017-04-11 13:46:53 +01:00
parent e6f63a22a3
commit 44bba45c7b
5 changed files with 26 additions and 8 deletions

12
lantern/error.py Normal file
View file

@ -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)

View file

@ -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

View file

@ -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)

View file

@ -0,0 +1,2 @@
<h1>Error</h1>
<p>{{ error }}</p>

View file

@ -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]