From f8addb6a19711394aceb2aae5c6496da4bc86cf2 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Sun, 15 Oct 2017 17:34:38 +0300 Subject: Refactor: add helper functions to construct apifw.Responses --- ick2/controllerapi.py | 70 +++++++++++++++++++++++++-------------------------- 1 file changed, 35 insertions(+), 35 deletions(-) (limited to 'ick2/controllerapi.py') diff --git a/ick2/controllerapi.py b/ick2/controllerapi.py index 7d43fda..1e7c488 100644 --- a/ick2/controllerapi.py +++ b/ick2/controllerapi.py @@ -68,15 +68,7 @@ class ControllerAPI: ] def get_version(self, *args, **kwargs): - return apifw.Response({ - 'status': apifw.HTTP_OK, - 'body': { - 'version': ick2.__version__, - }, - 'headers': { - 'Content-Type': 'application/json', - }, - }) + return OK({'version': ick2.__version__}) def get_callback(self, callback): # pragma: no cover def wrapper(content_type, body, **kwargs): @@ -85,31 +77,15 @@ class ControllerAPI: del kwargs['raw_uri_path'] body = callback(**kwargs) except ick2.NotFound as e: - return apifw.Response({ - 'status': apifw.HTTP_NOT_FOUND, - 'body': str(e), - 'headers': [], - }) - return apifw.Response({ - 'status': apifw.HTTP_OK, - 'body': body, - 'headers': { - 'Content-Type': 'application/json', - }, - }) + return not_found(e) + return OK(body) return wrapper def post_callback(self, callback): # pragma: no cover def wrapper(content_type, body, **kwargs): body = callback(body) ick2.log.log('trace', msg_text='returned body', body=repr(body)) - return apifw.Response({ - 'status': apifw.HTTP_CREATED, - 'body': body, - 'headers': { - 'Content-Type': 'application/json', - }, - }) + return created(body) return wrapper def put_callback(self, callback): # pragma: no cover @@ -118,13 +94,7 @@ class ControllerAPI: del kwargs['raw_uri_path'] body = callback(body, **kwargs) ick2.log.log('trace', msg_text='returned body', body=repr(body)) - return apifw.Response({ - 'status': apifw.HTTP_OK, - 'body': body, - 'headers': { - 'Content-Type': 'application/json', - }, - }) + return OK(body) return wrapper def get_projects(self): @@ -145,3 +115,33 @@ class ControllerAPI: def delete_projects(self, project): self._state.remove_project(project) + + +def response(status_code, body, headers): # pragma: no cover + obj = { + 'status': status_code, + 'body': body, + 'headers': headers, + } + return apifw.Response(obj) + + +def OK(body): # pragma: no cover + headers = { + 'Content-Type': 'application/json', + } + return response(apifw.HTTP_OK, body, headers) + + +def not_found(error): # pragma: no cover + headers = { + 'Content-Type': 'text/plain', + } + return response(apifw.HTTP_NOT_FOUND, str(error), headers) + + +def created(body): # pragma: no cover + headers = { + 'Content-Type': 'application/json', + } + return response(apifw.HTTP_CREATED, body, headers) -- cgit v1.2.1