Commit ad20beac authored by Per Cederqvist's avatar Per Cederqvist
Browse files

Use exceptions for non-200 responses.

This simplifies the code slightly.
parent 4fbfcd4f
......@@ -29,19 +29,43 @@ def os_path_split_asunder(path):
return parts
class Response(Exception):
def __init__(self, code, headers, body=""):
self.__code = code
self.__headers = headers
self.__body = body
def response(self, start_response):
start_response(self.__code, self.__headers)
return [self.__body]
class MethodNotAllowed(Response):
def __init__(self, allowed):
super().__init__("405 Method Not Allowed", [('Allow', allowed)])
class MovedPermanently(Response):
def __init__(self, location):
super().__init__("301 Moved Permanently", [("Location", location)])
class NotFound(Response):
def __init__(self):
super().__init__("404 Not Found", [])
def application(environ, start_response):
return process_request(environ, start_response)
except Response as r:
return r.response(start_response)
def process_request(environ, start_response):
if environ["REQUEST_METHOD"] not in ["GET", "POST"]:
start_response("405 Method Not Allowed",
[('Allow', 'GET')])
return []
raise MethodNotAllowed('GET, POST')
path = environ['PATH_INFO']
# We want a trailing slash at the root.
if path == "" and environ.get("SCRIPT_NAME", "") != "":
start_response("301 Moved Permanently",
[("Location", environ["SCRIPT_NAME"] + "/")])
return []
raise MovedPermanently(environ["SCRIPT_NAME"] + "/")
parts = os_path_split_asunder(path)
if len(parts) > 0 and parts[0] == "/":
......@@ -65,9 +89,7 @@ def application(environ, start_response):
return MP3_OPS[ops[0]](environ, start_response,
rel_base, ops[1:])
start_response("404 Not found", [])
return []
raise NotFound()
if stat.S_ISDIR(status.st_mode):
return handle_directory(environ, start_response,
......@@ -76,13 +98,11 @@ def application(environ, start_response):
return handle_file(environ, start_response,
start_response("404 Not found", [])
return []
raise NotFound()
def convert(environ, start_response, rel_base, ops):
if len(ops) > 0:
start_response("404 Not found", [])
return []
raise NotFound()
if environ["REQUEST_METHOD"] == "GET":
start_response("200 OK",
......@@ -93,8 +113,7 @@ def convert(environ, start_response, rel_base, ops):
if environ["REQUEST_METHOD"] != "POST":
start_response("405 Method Not Allowed",
[('Allow', 'GET, POST')])
raise MethodNotAllowed('GET, POST')
c = multiprocessing.connection.Client(mp3wavcfg.socketpath, 'AF_UNIX')
c.send(("encode", rel_base))
......@@ -103,10 +122,7 @@ def convert(environ, start_response, rel_base, ops):
if msg[0] != "progress":
start_response("301 Moved Permanently",
[("Content-Type", "text/plain"),
("Location", "..")])
return ["File converted to mp3"]
raise MovedPermanently("..")
MP3_OPS = {
'convert': convert,
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment