# HG changeset patch # User Björn Ricks # Date 1413981511 -7200 # Node ID 6d511e93a331bc80702289f207ea609e653395d0 # Parent a1100ec32be26ec2a72c826bc1d2aecd3abfdaa3 Return requested format when an error has occured Introduce ErrorResponse class which returns the error in the format as requested. diff -r a1100ec32be2 -r 6d511e93a331 odfcast/convert.py --- 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)