def _handle_exception(self, exception): """Called within an except block to allow converting exceptions to arbitrary responses. Anything returned (except None) will be used as response.""" try: return super(ApiJsonRequest, self)._handle_exception(exception) except Exception: if not isinstance( exception, (odoo.exceptions.Warning, SessionExpiredException, odoo.exceptions.except_orm, werkzeug.exceptions.NotFound)): _logger.exception("Exception during JSON request handling.") error = { 'code': 200, 'message': "Odoo Server Error", 'data': serialize_exception(exception) } if isinstance(exception, werkzeug.exceptions.NotFound): error['http_status'] = 404 error['code'] = 404 error['message'] = "404: Not Found" if isinstance(exception, AuthenticationError): error['code'] = 100 error['message'] = "Odoo Session Invalid" if isinstance(exception, SessionExpiredException): error['code'] = 100 error['message'] = "Odoo Session Expired" return self._json_response(error=error)
def _handle_exception(self, exception): """Called within an except block to allow converting exceptions to arbitrary responses. Anything returned (except None) will be used as response.""" try: return super(ApiJsonRequest, self)._handle_exception(exception) except Exception: if not isinstance( exception, ( odoo.exceptions.Warning, SessionExpiredException, odoo.exceptions.except_orm, werkzeug.exceptions.NotFound, ), ): _logger.exception("Exception during JSON request handling.") error = { "code": 500, "message": "Odoo Server Error", "data": serialize_exception(exception), "openapi_message": exception.args[0], } if isinstance(exception, psycopg2.InternalError): error["message"] = "500: Internal Server Error" if isinstance(exception, werkzeug.exceptions.NotFound): error["code"] = 404 error["message"] = "404: Not Found" if isinstance(exception, AuthenticationError): error["code"] = 100 error["message"] = "Odoo Session Invalid" if isinstance(exception, SessionExpiredException): error["code"] = 100 error["message"] = "Odoo Session Expired" return self._json_response(error=error)
def report_download(self, data, token, context=None): requestcontent = json.loads(data) url, report_type = requestcontent[0], requestcontent[1] if report_type == "qweb-xml": try: reportname = url.split("/report/xml/")[1].split("?")[0] docids = None if "/" in reportname: reportname, docids = reportname.split("/") if docids: # Generic report: response = self.report_routes(reportname, docids=docids, converter="xml", context=context) else: # Particular report: # decoding the args represented in JSON data = dict(url_decode(url.split("?")[1]).items()) if "context" in data: context = json.loads(context or "{}") data_context = json.loads(data.pop("context")) context = json.dumps({**context, **data_context}) response = self.report_routes(reportname, converter="xml", context=context, **data) report_obj = request.env["ir.actions.report"] report = report_obj._get_report_from_name(reportname) filename = "%s.xml" % (report.name) if docids: ids = [int(doc_id) for doc_id in docids.split(",")] records = request.env[report.model].browse(ids) if report.print_report_name and not len(records) > 1: report_name = safe_eval(report.print_report_name, { "object": records, "time": time }) filename = "{}.xml".format(report_name) response.headers.add("Content-Disposition", content_disposition(filename)) response.set_cookie("fileToken", token) return response except Exception as e: se = serialize_exception(e) error = { "code": 200, "message": "Odoo Server Error", "data": se } return request.make_response(html_escape(json.dumps(error))) else: return super().report_download(data, token, context)
def index(self, data): try: return self.base(data) except Exception as exc: _logger.exception("Exception during request handling.") payload = json.dumps({ 'code': 200, 'message': "Odoo Server Error", 'data': http.serialize_exception(exc) }) raise InternalServerError(payload) from exc
def report_download(self, data, token): requestcontent = json.loads(data) url, report_type = requestcontent[0], requestcontent[1] if report_type == 'qweb-xml': try: reportname = url.split('/report/xml/')[1].split('?')[0] docids = None if '/' in reportname: reportname, docids = reportname.split('/') if docids: # Generic report: response = self.report_routes(reportname, docids=docids, converter='xml') else: # Particular report: # decoding the args represented in JSON data = url_decode(url.split('?')[1]).items() response = self.report_routes(reportname, converter='xml', **dict(data)) report_obj = request.env['ir.actions.report'] report = report_obj._get_report_from_name(reportname) filename = "%s.xml" % (report.name) if docids: ids = [int(x) for x in docids.split(",")] records = request.env[report.model].browse(ids) if report.print_report_name and not len(records) > 1: report_name = safe_eval(report.print_report_name, { 'object': records, 'time': time }) filename = "%s.xml" % (report_name) response.headers.add('Content-Disposition', content_disposition(filename)) response.set_cookie('fileToken', token) return response except Exception as e: se = serialize_exception(e) error = { 'code': 200, 'message': "Odoo Server Error", 'data': se } return request.make_response(html_escape(json.dumps(error))) else: return super(ReportController, self).report_download(data, token)
def report(self, output_format, report_name, token, report_id=False, **kw): uid = request.session.uid coa = request.env['account.open.chart'].sudo(uid).browse(report_id) try: if output_format == 'pdf': response = request.make_response( coa.with_context(active_id=report_id).get_pdf(report_id), headers=[('Content-Type', 'application/pdf'), ('Content-Disposition', 'attachment; filename=coa_report.pdf;')]) response.set_cookie('fileToken', token) return response except Exception as e: se = serialize_exception(e) error = {'code': 200, 'message': 'Odoo Server Error', 'data': se} return request.make_response(html_escape(json.dumps(error)))
def _report_routes_xlsx(self, reportname, docids=None, converter=None, **data): try: report = request.env["ir.actions.report"]._get_report_from_name( reportname) context = dict(request.env.context) if docids: docids = [int(i) for i in docids.split(",")] if data.get("options"): data.update(json.loads(data.pop("options"))) if data.get("context"): # Ignore 'lang' here, because the context in data is the one # from the webclient *but* if the user explicitely wants to # change the lang, this mechanism overwrites it. data["context"] = json.loads(data["context"]) if data["context"].get("lang"): del data["context"]["lang"] context.update(data["context"]) if not docids and data["context"].get("active_ids"): docids = data["context"].get("active_ids") xlsx = report.with_context(context)._render_xlsx(docids, data=data)[0] report_name = report.report_file if report.print_report_name and docids and not len(docids) > 1: obj = request.env[report.model].browse(docids[0]) report_name = safe_eval(report.print_report_name, {"object": obj}) xlsxhttpheaders = [ ( "Content-Type", "application/vnd.openxmlformats-" "officedocument.spreadsheetml.sheet", ), ("Content-Length", len(xlsx)), ("Content-Disposition", content_disposition(report_name + ".xlsx")), ] return request.make_response(xlsx, headers=xlsxhttpheaders) except Exception as e: se = serialize_exception(e) error = {"code": 200, "message": "Odoo Server Error", "data": se} return request.make_response(html_escape(json.dumps(error)))
def _handle_exception(self, exception): """Called within an except block to allow converting exceptions to arbitrary responses. Anything returned (except None) will be used as response.""" try: return WebRequest._handle_exception(self, exception) except Exception: if not isinstance( exception, (odoo.exceptions.Warning, SessionExpiredException)): _logger.exception("Exception during JSON request handling.") error = { 'code': 500, 'message': "Odoo Server Error", 'data': serialize_exception(exception) } if isinstance(exception, AuthenticationError): error['code'] = 100 error['message'] = "Odoo Session Invalid" if isinstance(exception, odoo.exceptions.AccessDenied): error['code'] = 401 error['message'] = "Unauthorized" if isinstance(exception, SessionExpiredException): error['code'] = 100 error['message'] = "Odoo Session Expired" if isinstance(exception, werkzeug.exceptions.NotFound): error['code'] = 404 error['message'] = "Not found" error.pop('data', None) if isinstance(exception, werkzeug.exceptions.BadRequest): error['code'] = 400 error['message'] = "Bad Request" if isinstance(exception, odoo.exceptions.AccessError): error['code'] = 403 error['message'] = "Forbidden" error.pop('data', None) if isinstance(exception, werkzeug.exceptions.MethodNotAllowed): error['code'] = 405 error['message'] = "MethodNotAllowed" if isinstance(exception, exceptions.RestException): error['code'] = exception.code error['message'] = exception.message error.pop('data', None) return self._json_response(error=error)
def get_report_xlsx(self, model, options, output_format, token, report_name, **kw): uid = request.session.uid report_obj = request.env[model].with_user(uid) options = json.loads(options) try: if output_format == 'xlsx': response = request.make_response( None, headers=[('Content-Type', 'application/vnd.ms-excel'), ('Content-Disposition', content_disposition(report_name + '.xlsx'))]) report_obj.get_xlsx_report(options, response) response.set_cookie('fileToken', token) return response except Exception as e: se = serialize_exception(e) error = {'code': 200, 'message': 'Odoo Server Error', 'data': se} return request.make_response(html_escape(json.dumps(error)))
def report(self, output_format, report_name=False, **kw): uid = request.session.uid domain = [('create_uid', '=', uid)] stock_traceability = request.env[ 'stock.traceability.report'].with_user(uid).search(domain, limit=1) line_data = json.loads(kw['data']) try: if output_format == 'pdf': response = request.make_response( stock_traceability.with_context( active_id=kw['active_id'], active_model=kw['active_model']).get_pdf(line_data), headers=[('Content-Type', 'application/pdf'), ('Content-Disposition', 'attachment; filename=' + 'stock_traceability' + '.pdf;')]) return response except Exception as e: se = http.serialize_exception(e) error = {'code': 200, 'message': 'Odoo Server Error', 'data': se} return request.make_response(html_escape(json.dumps(error)))
def _handle_exception(self, exception): try: return super(http.JsonRequest, self)._handle_exception(exception) except Exception: if not isinstance(exception, (odoo.exceptions.Warning, http.SessionExpiredException, odoo.exceptions.except_orm, werkzeug.exceptions.NotFound)): http._logger.exception("Exception during JSON request handling.") error = { 'code': 200, 'message': _("Odoo Server Error"), 'data': http.serialize_exception(exception) } if isinstance(exception, werkzeug.exceptions.NotFound): error['http_status'] = 404 error['code'] = 404 error['message'] = "404: Not Found" if isinstance(exception, http.AuthenticationError): error['code'] = 100 error['message'] = "Odoo Session Invalid" if isinstance(exception, http.SessionExpiredException): error['code'] = 100 error['message'] = "Odoo Session Expired" return self._json_response(error=error)
def report_download(self, data, context=None, token=None): # pylint: disable=unused-argument """This function is used by 'action_manager_report.js' in order to trigger the download of a pdf/controller report. :param data: a javascript array JSON.stringified containg report internal url ([0]) and type [1] :returns: Response with an attachment header """ requestcontent = json.loads(data) url, type_ = requestcontent[0], requestcontent[1] reportname = '???' try: if type_ in ['qweb-pdf', 'qweb-text']: converter = 'pdf' if type_ == 'qweb-pdf' else 'text' extension = 'pdf' if type_ == 'qweb-pdf' else 'txt' pattern = '/report/pdf/' if type_ == 'qweb-pdf' else '/report/text/' reportname = url.split(pattern)[1].split('?')[0] docids = None if '/' in reportname: reportname, docids = reportname.split('/') if docids: # Generic report: response = self.report_routes(reportname, docids=docids, converter=converter, context=context) else: # Particular report: data = url_parse(url).decode_query( cls=dict) # decoding the args represented in JSON if 'context' in data: context, data_context = json.loads( context or '{}'), json.loads(data.pop('context')) context = json.dumps({**context, **data_context}) response = self.report_routes(reportname, converter=converter, context=context, **data) report = request.env[ 'ir.actions.report']._get_report_from_name(reportname) filename = "%s.%s" % (report.name, extension) if docids: ids = [int(x) for x in docids.split(",")] obj = request.env[report.model].browse(ids) if report.print_report_name and not len(obj) > 1: report_name = safe_eval(report.print_report_name, { 'object': obj, 'time': time }) filename = "%s.%s" % (report_name, extension) response.headers.add('Content-Disposition', content_disposition(filename)) return response else: return except Exception as e: _logger.exception("Error while generating report %s", reportname) se = http.serialize_exception(e) error = {'code': 200, 'message': "Odoo Server Error", 'data': se} return request.make_response(html_escape(json.dumps(error)))
def _handle_exception(self, exception): """Format the errors to conform to GMC error types.""" error = { 'ErrorId': self.uuid, 'ErrorTimestamp': self.timestamp, 'ErrorClass': 'BusinessException', 'ErrorRetryable': False, 'ErrorModule': 'REST OnRamp', 'ErrorSubModule': 'Rest OnRamp Authorization', 'ErrorMethod': 'ValidateToken', 'ErrorLoggedInUser': '', 'RelatedRecordId': '' } try: super(JsonRequest, self)._handle_exception(exception) except werkzeug.exceptions.HTTPException: # General exception, send back the exception message error.update({ 'ErrorCode': exception.code, 'ErrorCategory': 'CommunicationError', 'ErrorMessage': exception.description, }) _logger.error(exception.description, exc_info=True) except exceptions.AccessDenied: # Access error error.update({ 'ErrorCode': 401, 'ErrorCategory': 'AuthorizationError', 'ErrorMessage': '401 Unauthorized', }) _logger.error('401 Unauthorized', exc_info=True) except AttributeError: # Raised if JSON could not be parsed or invalid body was received error.update({ 'ErrorCode': 400, 'ErrorSubModule': 'Rest OnRamp Message Validation', 'ErrorMethod': 'Message Validation', 'ErrorCategory': 'InputValidationError', 'ErrorMessage': exception.message, }) _logger.error(exception.message, exc_info=True) except AuthenticationError: error.update({ 'ErrorCode': 401, 'ErrorCategory': 'AuthenticationError', 'ErrorMessage': 'Session Invalid', }) _logger.error('Session Invalid', exc_info=True) except SessionExpiredException: error.update({ 'ErrorCode': 401, 'ErrorCategory': 'AuthenticationError', 'ErrorMessage': 'Session Expired', }) _logger.error('Session Expired', exc_info=True) except Exception: # Any other cases, lookup what exception type was raised. if not isinstance(exception, (exceptions.UserError)): _logger.exception( "Exception during JSON request handling.", exc_info=True) error.update({ 'ErrorCode': 500, 'ErrorCategory': 'ApplicationError', 'ErrorMessage': 'Odoo Server Error', }) finally: ONRAMP_LOGGER.error(serialize_exception(exception)) return self._json_response(error=error)