Mercurial > odfcast
changeset 42:6d511e93a331
Return requested format when an error has occured
Introduce ErrorResponse class which returns the error in the format as
requested.
author | Björn Ricks <bjoern.ricks@intevation.de> |
---|---|
date | Wed, 22 Oct 2014 14:38:31 +0200 |
parents | a1100ec32be2 |
children | 19f6a6d9cbed |
files | odfcast/convert.py |
diffstat | 1 files changed, 45 insertions(+), 7 deletions(-) [+] |
line wrap: on
line diff
--- a/odfcast/convert.py Mon Oct 20 16:16:53 2014 +0200 +++ b/odfcast/convert.py Wed Oct 22 14:38:31 2014 +0200 @@ -27,6 +27,36 @@ DEFAULT_MIMETYPE = "application/octet-stream" +class ErrorResponse(object): + + def __init__(self, title, details="", html_error_code=500): + self.title = title + self.details = details + self.html_error_code = html_error_code + + def __call__(self): + if self.is_wants_json(): + return self.json() + else: + return self.html() + + def json(self): + return json.dumps({ + "error": self.title, + "details": self.details + }), self.html_error_code + + def html(self): + return self.title, self.html_error_code + + def is_wants_json(self): + best = request.accept_mimetypes.best_match(['application/json', + 'text/html']) + return best == 'application/json' and \ + request.accept_mimetypes[best] > \ + request.accept_mimetypes['text/html'] + + class ConvertView(MethodView): def __init__(self, pyuno_driver_name="", hostname="localhost", port=2001): @@ -43,11 +73,15 @@ def post(self): ffile = request.files['file'] if not ffile.filename: - return "Please upload a file for conversion", 401 + error = ErrorResponse("Please upload a file for conversion", + html_error_code=401) + return error() fformat = request.form['format'] if not self.is_format_supported(fformat): - return "Format %s not allowed" % fformat, 401 + error = ErrorResponse("Format %s not allowed" % fformat, + html_error_code=401) + return error() datadict = self.get_datadict() @@ -58,20 +92,24 @@ if datadict: try: tfile = tempfile.NamedTemporaryFile() - t = Template(outfile, tfile) + t = Template(outfile, tfile, ignore_undefined_variables=True) t.render(datadict) outfile.close() outfile = tfile - except: + except Exception, e: log.exception("Template error") - return "Template error", 500 + error = ErrorResponse( + "Template error", details=str(e), html_error_code=500) + return error() if fformat != "odt": try: outfile = self.convert(outfile, fformat) - except: + except Exception, e: log.exception("Conversion error") - return "Conversion error", 500 + error = ErrorResponse( + "Conversion error", details=str(e), html_error_code=500) + return error() return Response(outfile, mimetype=mimetype)