Browse Source

Add error response

master
Jake Howard 4 years ago
parent
commit
44bba45c7b
  1. 12
      lantern/error.py
  2. 9
      lantern/handle.py
  3. 8
      lantern/route.py
  4. 2
      lantern/templates/error.html
  5. 3
      setup.py

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

9
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

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

2
lantern/templates/error.html

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

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

Loading…
Cancel
Save