def test_03_web_content_filename(self): """This test makes sure the Content-Disposition header matches the given filename""" att = self.env['ir.attachment'].create({ 'datas': b'R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=', 'name': 'testFilename.gif', 'public': True, 'mimetype': 'image/gif' }) # CASE: no filename given res = self.url_open('/web/image/%s/0x0/?download=true' % att.id) self.assertEqual(res.headers['Content-Disposition'], content_disposition('testFilename.gif')) # CASE: given filename without extension res = self.url_open('/web/image/%s/0x0/custom?download=true' % att.id) self.assertEqual(res.headers['Content-Disposition'], content_disposition('custom.gif')) # CASE: given filename and extention res = self.url_open('/web/image/%s/0x0/custom.png?download=true' % att.id) self.assertEqual(res.headers['Content-Disposition'], content_disposition('custom.png'))
def get_report(self, model, options, output_format, token, report_id=None, **kw): uid = request.session.uid report_obj = request.env[model].sudo(uid) options = json.loads(options) if report_id: report_obj = report_obj.browse(int(report_id)) report_name = report_obj.get_report_filename(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(options, response) if output_format == 'pdf': response = request.make_response( report_obj.get_pdf(options), headers=[('Content-Type', 'application/pdf'), ('Content-Disposition', content_disposition(report_name + '.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(self, reportname, docids=None, converter=None, **data): if converter not in ['xlsx', 'txt', 'zip']: return super(ReportController, self).report_routes( reportname, docids, converter, **data ) 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'): data['context'] = json.loads(data['context']) if data['context'].get('lang'): del data['context']['lang'] context.update(data['context']) if converter == 'xlsx': body = report.with_context(context).render_xlsx( docids, data=data )[0] bodyhttpheaders = [ ('Content-Type', 'application/vnd.openxmlformats-' 'officedocument.spreadsheetml.sheet'), ('Content-Length', len(body)), ( 'Content-Disposition', content_disposition(report.report_file + '.xlsx') ) ] elif converter == 'txt': report_name = report.render_txt_name(docids, data=data) or '%s.txt'%( report.report_file ) body = report.with_context(context).render_txt( docids, data=data )[0] bodyhttpheaders = [ ('Content-Type', 'text/plain'), ('Content-Length', len(body)), ( 'Content-Disposition', content_disposition( report_name ) ) ] elif converter == 'zip': body = report.with_context(context).render_zip( docids, data=data )[0] bodyhttpheaders = [ ('Content-Type', 'application/octet-stream'), ('Content-Length', len(body)), ( 'Content-Disposition', content_disposition(report.report_file + '.zip') ) ] return request.make_response(body, headers=bodyhttpheaders) """
def _generate_report(self, user_input, download=True): report = request.env.ref('survey.certification_report').sudo().render_qweb_pdf([user_input.id], data={'report_type': 'pdf'})[0] report_content_disposition = content_disposition('Certification.pdf') if not download: content_split = report_content_disposition.split(';') content_split[0] = 'inline' report_content_disposition = ';'.join(content_split) return request.make_response(report, headers=[ ('Content-Type', 'application/pdf'), ('Content-Length', len(report)), <<<<<<< HEAD ] reporthttpheaders.append(('Content-Disposition', content_disposition('Certification.pdf'))) return request.make_response(report, headers=reporthttpheaders) def _prepare_result_dict(self, survey, current_filters=None): """Returns dictionary having values for rendering template""" current_filters = current_filters if current_filters else [] result = {'page_ids': []} # First append questions without page questions_without_page = [self._prepare_question_values(question,current_filters) for question in survey.question_ids if not question.page_id] if questions_without_page: result['page_ids'].append({'page': request.env['survey.question'], 'question_ids': questions_without_page}) # Then, questions in sections for page in survey.page_ids: page_dict = {'page': page, 'question_ids': [self._prepare_question_values(question,current_filters) for question in page.question_ids]} result['page_ids'].append(page_dict) if survey.scoring_type in ['scoring_with_answers', 'scoring_without_answers']: scoring_data = self._get_scoring_data(survey) result['success_rate'] = scoring_data['success_rate'] result['scoring_graph_data'] = json.dumps(scoring_data['graph_data']) return result def _prepare_question_values(self, question, current_filters): Survey = request.env['survey.survey'] return { 'question': question, 'input_summary': Survey.get_input_summary(question, current_filters), 'prepare_result': Survey.prepare_result(question, current_filters), 'graph_data': self._get_graph_data(question, current_filters), } def _get_filter_data(self, post): """Returns data used for filtering the result""" filters = [] for ids in post: #if user add some random data in query URI, ignore it ======= ('Content-Disposition', report_content_disposition), ])
def base(self, data, token): params = json.loads(data) header, chart_data = operator.itemgetter('header', 'chart_data')(params) chart_data = json.loads(chart_data) # Model = request.env[model].with_context(import_compat=import_compat, **params.get('context', {})) # records = Model.browse(ids) or Model.search(domain, offset=0, limit=False, order=False) # # if not Model._is_an_ordinary_table(): # fields = [field for field in fields if field['name'] != 'id'] # field_names = [f['name'] for f in fields] # import_data = records.export_data(field_names, self.raw_data).get('datas',[]) # if import_compat: # columns_headers = field_names # else: # columns_headers = [val['label'].strip() for val in fields] # columns_headers = [header] chart_data['labels'].insert(0, 'Measure') columns_headers = chart_data['labels'] import_data = [] for dataset in chart_data['datasets']: dataset['data'].insert(0, dataset['label']) import_data.append(dataset['data']) return request.make_response( self.from_data(columns_headers, import_data), headers=[('Content-Disposition', content_disposition(self.filename(header))), ('Content-Type', self.content_type)], cookies={'fileToken': token})
def report_routes(self, reportname, docids=None, converter=None, **data): if converter not in ['aeroo', 'qweb-aeroo']: return super(ReportController, self).report_routes(reportname, docids, converter, **data) context = dict(request.env.context) report = request.env['ir.actions.report']._get_report_from_name( reportname) context.update({'preview': 'ABC'}) 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'): data['context'] = json.loads(data['context']) if data['context'].get('lang'): del data['context']['lang'] context.update(data['context']) file_data, out_code, filename = report.with_context( context).render_aeroo(docids, data=data) httpheaders = [('Content-Type', self.MIMETYPES.get(out_code, 'application/octet-stream')), ('Content-Length', len(file_data)), ('Content-Disposition', content_disposition(filename))] return request.make_response(file_data, headers=httpheaders)
def report_routes(self, reportname, docids=None, converter=None, **data): if converter == "xlsx": 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"): data["context"] = json.loads(data["context"]) if data["context"].get("lang"): del data["context"]["lang"] context.update(data["context"]) xlsx = report.with_context(context)._render_xlsx(docids, data=data)[0] report_name = report.report_file if report.print_report_name 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) return super(ReportController, self).report_routes( reportname, docids, converter, **data )
def _get_binary_content(self, invoice): """ Generate the invoice report.... :param invoice: :returns: (headers, content) """ # ensure the report is generated invoice_report_def = invoice.invoice_print() report_name = invoice_report_def["report_name"] report_type = invoice_report_def["report_type"] report = self._get_report(report_name, report_type) content, extension = report.render( invoice.ids, data={"report_type": report_type} ) filename = self._get_binary_content_filename( invoice, report, extension ) mimetype = mimetypes.guess_type(filename) if mimetype: mimetype = mimetype[0] headers = [ ("Content-Type", mimetype), ("X-Content-Type-Options", "nosniff"), ("Content-Disposition", content_disposition(filename)), ("Content-Length", len(content)), ] return headers, content
def _show_report(self, model, report_type, report_ref, download=False): """ Modificamos el metodo generico para intentar obtener report con "get_report" antes de usar el report_ref Ademas agregamos compatibilidad con aeroo (por ahora solo descarga archivo, deberia previsualizarlo) """ if report_type not in ('html', 'pdf', 'text'): raise UserError("Invalid report type: %s" % report_type) # por ahora, comoo no podemos previsualizar reportes de aeroo, si se pide reporte html/text devolvemos reportes # nativos de odoo. Una vez implementado lo de abajo se puede usar siempre el get_report # report_sudo = model.sudo().get_report() report_sudo = report_type == 'pdf' and hasattr( model.sudo(), 'get_report') and model.sudo().get_report() or False # if we found a new report use it, if not use default report_ref report_ref = report_sudo and report_sudo.get_external_id()[ report_sudo.id] or report_ref # now we fix aerro rendering report_sudo = request.env.ref(report_ref).sudo() if report_sudo.report_type != 'aeroo': return super()._show_report(model, report_type, report_ref, download=False) # TODO incorporarar que se pueda previsualizar el reporte sin descargar rset = report_sudo.render_aeroo([model.id], data={}) mimetype = ReportController.MIMETYPES.get(rset[1], 'application/octet-stream') httpheaders = [('Content-Disposition', content_disposition(rset[2])), ('Content-Type', mimetype), ('Content-Length', len(rset[0]))] return request.make_response(rset[0], headers=httpheaders)
def portal_my_invoice_report(self, invoice_id, access_token=None, **kw): try: invoice_sudo = self._document_check_access('account.invoice', invoice_id, access_token) except (AccessError, MissingError): return request.redirect('/my') # print report as sudo, since it require access to taxes, payment term, ... and portal # does not have those access rights. accountInvoiceReport = request.env.ref( 'account.account_invoices').sudo() report_type = kw.get('report_type', 'pdf') method_name = 'render_qweb_%s' % (report_type) if hasattr(accountInvoiceReport, method_name): invoice_report = getattr(accountInvoiceReport, method_name)([invoice_sudo.id], data={ 'report_type': report_type })[0] reporthttpheaders = [ ('Content-Type', 'application/pdf' if report_type == 'pdf' else 'text/html'), ('Content-Length', len(invoice_report)), ] if report_type == 'pdf' and not kw.get('print'): filename = "%s.pdf" % (re.sub( '\W+', '-', invoice_sudo._get_printed_report_name())) reporthttpheaders.append(('Content-Disposition', http.content_disposition(filename))) return request.make_response(invoice_report, headers=reporthttpheaders) raise NotFound()
def report_routes(self, reportname, docids=None, converter=None, **data): report = request.env['ir.actions.report']._get_report_from_name( reportname) if converter == 'xlsx' and not report: 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']) context['report_name'] = reportname xlsx = report.with_context(context).render_xlsx(docids, data=data)[0] report_file = context.get('report_file') if not report_file: active_model = context.get('active_model', 'export') report_file = active_model.replace('.', '_') xlsxhttpheaders = [('Content-Type', 'application/vnd.openxmlformats-' 'officedocument.spreadsheetml.sheet'), ('Content-Length', len(xlsx)), ('Content-Disposition', content_disposition(report_file + '.xlsx'))] return request.make_response(xlsx, headers=xlsxhttpheaders) return super(ReportController, self).report_routes(reportname, docids, converter, **data)
def _make_zip(self, name, documents): """returns zip files for the Document Inspector and the portal. :param name: the name to give to the zip file. :param documents: files (documents.document) to be zipped. :return: a http response to download a zip file. """ stream = io.BytesIO() try: with zipfile.ZipFile(stream, 'w') as doc_zip: for document in documents: if document.type != 'binary': continue status, content, filename, mimetype, filehash = request.env[ 'ir.http']._binary_record_content( document, field='datas', filename=None, filename_field='name', default_mimetype='application/octet-stream') doc_zip.writestr(filename, base64.b64decode(content), compress_type=zipfile.ZIP_DEFLATED) except zipfile.BadZipfile: logger.exception("BadZipfile exception") content = stream.getvalue() headers = [('Content-Type', 'zip'), ('X-Content-Type-Options', 'nosniff'), ('Content-Length', len(content)), ('Content-Disposition', content_disposition(name))] return request.make_response(content, headers)
def download_report(self, data, token): result = json.loads(data) pdf = result[0] output_type = result[1] reportname = result[2] en = base64.b64encode(pdf.encode('latin1', 'replace')) res = base64.b64decode(en) pdfhttpheaders = [('Content-Length', len(res)), ('Content-Type', 'application/download')] response = request.make_response(res, pdfhttpheaders, cookies={'fileToken': token}) report = request.env['ir.actions.report']._get_report_from_name( reportname) print('name =', report.name) filename = "%s.%s" % (report.name, output_type) response.headers.add('Content-Disposition', content_disposition(filename)) return response
def report_routes(self, reportname, docids=None, converter=None, **data): if converter == 'xlsx': 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'): data['context'] = json.loads(data['context']) if data['context'].get('lang'): del data['context']['lang'] context.update(data['context']) xlsx = report.with_context(context).render_xlsx( docids, data=data )[0] xlsxhttpheaders = [ ('Content-Type', 'application/vnd.openxmlformats-' 'officedocument.spreadsheetml.sheet'), ('Content-Length', len(xlsx)), ( 'Content-Disposition', content_disposition(report.report_file + '.xlsx') ) ] return request.make_response(xlsx, headers=xlsxhttpheaders) return super(ReportController, self).report_routes( reportname, docids, converter, **data )
def _binary_set_headers(self, status, content, filename, mimetype, unique, filehash=None, download=False): headers = [('Content-Type', mimetype), ('X-Content-Type-Options', 'nosniff')] # cache etag = bool(request) and request.httprequest.headers.get( 'If-None-Match') status = status or 200 if filehash: headers.append(('ETag', filehash)) if etag == filehash and status == 200: status = 304 headers.append( ('Cache-Control', 'max-age=%s' % (http.STATIC_CACHE_LONG if unique else 0))) # content-disposition default name if download: headers.append( ('Content-Disposition', content_disposition(filename))) return (status, headers, content)
def get_report_xlsx(self, model, output_format, report_name, **kw): uid = request.session.uid report_obj = request.env[model].sudo(uid) data = { 'start_date': time.strftime('%Y-%m-01'), 'end_date': datetime.datetime.now() } options = json.loads(json.dumps(data, default=date_utils.json_default)) 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) 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 OAS_json_spec_download(self, namespace_name, **kwargs): ensure_db() namespace = (http.request.env["openapi.namespace"].sudo().search([ ("name", "=", namespace_name) ])) if not namespace: raise werkzeug.exceptions.NotFound() if namespace.token != kwargs.get("token"): raise werkzeug.exceptions.Forbidden() response_params = {"headers": [("Content-Type", "application/json")]} if "download" in kwargs: response_params = { "headers": [ ("Content-Type", "application/octet-stream; charset=binary"), ("Content-Disposition", http.content_disposition("swagger.json")), ], "direct_passthrough": True, } return werkzeug.wrappers.Response(json.dumps( namespace.get_OAS(), default=date_utils.json_default), status=200, **response_params)
def report_routes(self, reportname, docids=None, converter=None, **data): if converter == 'fillpdf': 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']) pdf = report.with_context(context).render_fillpdf(docids, data=data)[0] pdfhttpheaders = [ ('Content-Type', 'application/pdf'), ('Content-Length', len(pdf)), ('Content-Disposition', content_disposition(report.report_file + '.pdf')) ] return request.make_response(pdf, headers=pdfhttpheaders) return super(ReportController, self).report_routes(reportname, docids, converter, **data)
def report_routes(self, reportname, docids=None, converter=None, **data): report = request.env["ir.actions.report"]._get_report_from_name( reportname) if converter == "xlsx" and not report: 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"): data["context"] = json.loads(data["context"]) context.update(data["context"]) context["report_name"] = reportname xlsx = report.with_context(context)._render_xlsx(docids, data=data)[0] report_file = context.get("report_file") if not report_file: active_model = context.get("active_model", "export") report_file = active_model.replace(".", "_") xlsxhttpheaders = [ ( "Content-Type", "application/vnd.openxmlformats-" "officedocument.spreadsheetml.sheet", ), ("Content-Length", len(xlsx)), ("Content-Disposition", content_disposition(report_file + ".xlsx")), ] return request.make_response(xlsx, headers=xlsxhttpheaders) return super().report_routes(reportname, docids, converter, **data)
def _get_binary_content(self, target, params=None): """ Generate the report for the given target :param target: :param params: dict :returns: (headers, content) """ # Ensure the report is generated target_report_def = self._get_report_action(target, params=params) report_name = target_report_def.get("report_name") report_type = target_report_def.get("report_type") report = self._get_report(report_name, report_type) content, extension = report.render(target.ids, data={"report_type": report_type}) filename = self._get_binary_content_filename(target, report, extension, params=params) mimetype = mimetypes.guess_type(filename) if mimetype: mimetype = mimetype[0] headers = [ ("Content-Type", mimetype), ("X-Content-Type-Options", "nosniff"), ("Content-Disposition", content_disposition(filename)), ("Content-Length", len(content)), ] return headers, content
def report_routes(self, reportname, docids=None, converter=None, **data): if converter == 'xlsx': 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']) xlsx = report.with_context(context).render_xlsx(docids, data=data)[0] report_name = report.report_file if report.print_report_name and not len(docids) > 1: obj = request.env[report.model].browse(docids[0]) report_name = safe_eval(report.print_report_name, { 'object': obj, 'time': time }) 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) return super(ReportController, self).report_routes(reportname, docids, converter, **data)
def report_download(self, data, token): response = super(OpenedunavDownloadController, self).report_download(data, token) # if we got another content disposition before, ditch the one added # by super() requestcontent = json.loads(data) url, type = requestcontent[0], requestcontent[1] try: if type == 'qweb-pdf': reportname = url.split('/report/pdf/')[1].split('?')[0] docids = None if '/' in reportname: reportname, docids = reportname.split('/') if not docids: cr, uid = request.cr, request.uid report = request.registry['report']._get_report_from_name( cr, uid, reportname) data = dict(url_decode(url.split('?')[1]).items()) data = json.loads(data.pop('options')) response.headers[ 'Content-Disposition'] = content_disposition( data['download_name']) return response except Exception as e: exc_info = sys.exc_info() se = traceback.format_exception(*exc_info) error = {'code': 200, 'message': "Odoo Server Error", 'data': se} return request.make_response(html_escape(json.dumps(error))) return response
def report_routes(self, reportname, docids=None, converter=None, **data): if converter == "jasperserver": 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"]) pdf = report.with_context(context).render_jasperserver_pdf( docids, data=data)[0] filename = "{}.{}".format(report.name, "pdf") if report.print_report_name and not len(docids) > 1: obj = request.env[report.model].browse(docids) report_name = safe_eval(report.print_report_name, { "object": obj, "time": time }) filename = "{}.{}".format(report_name, "pdf") pdfhttpheaders = [ ("Content-Type", "application/pdf"), ("Content-Length", len(pdf)), ("Content-Disposition", content_disposition(filename)), ] return request.make_response(pdf, headers=pdfhttpheaders) return super(ReportController, self).report_routes(reportname, docids, converter, **data)
def download_document(self, model, id, **kwargs): summ = request.env[model].browse(int(id)) file = base64.b64decode(summ.datas) file_name = summ.datas_fname return request.make_response( file, [('Content-Type', 'text/plain'), ('Content-Disposition', content_disposition(file_name))])
def portal_my_summary(self, **kw): partner = request.env.user.partner_id to_date = fields.Datetime.to_string(datetime.now()) from_date = fields.Datetime.to_string(datetime.now() + timedelta(days=-30)) report_data = { 'secondary_currency': False, 'financial_amounts': False, 'result_selection': 'all', 'company_type': 'group_by_company', 'company_id': False, 'from_date': from_date, 'to_date': to_date, 'historical_full': True, 'show_invoice_detail': False, 'lang': partner.lang, } xls = request.env.ref('account_debt_management.account_debt_report' ).sudo().with_context(report_data).render( [partner.id], data=report_data)[0] xlshttpheaders = [('Content-Type', 'application/vnd.ms-excel'), ('Content-Length', len(xls)), ('Content-Disposition', content_disposition('Resumen de Cuenta' + '.xls'))] return request.make_response(xls, headers=xlshttpheaders)
def survey_get_certification(self, survey_id, **kwargs): """ The certification document can be downloaded as long as the user has succeeded the certification """ survey = request.env['survey.survey'].sudo().search([ ('id', '=', survey_id), ('certificate', '=', True) ]) if not survey: # no certification found return werkzeug.utils.redirect("/") succeeded_attempt = request.env['survey.user_input'].sudo().search([ ('partner_id', '=', request.env.user.partner_id.id), ('survey_id', '=', survey_id), ('quizz_passed', '=', True) ], limit=1) if not succeeded_attempt: raise UserError(_("The user has not succeeded the certification")) report_sudo = request.env.ref('survey.certification_report').sudo() report = report_sudo.render_qweb_pdf([succeeded_attempt.id], data={'report_type': 'pdf'})[0] reporthttpheaders = [ ('Content-Type', 'application/pdf'), ('Content-Length', len(report)), ] reporthttpheaders.append(('Content-Disposition', content_disposition('Certification.pdf'))) return request.make_response(report, headers=reporthttpheaders)
def report_routes(self, reportname, docids=None, converter=None, **data): # if it's not Aeroo Reports fall back to original reporting engine if converter != 'aeroo': return super(ReportController, self).report_routes(reportname, docids, converter, **data) # Aeroo Reports starts here report_obj = request.env['ir.actions.report'] report = report_obj._get_report_from_name(reportname) context = dict(request.env.context) # report_data = {} 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'): data['context'] = json.loads(data['context']) if data['context'].get('lang'): del data['context']['lang'] context.update(data['context']) rset = report.with_context(context).render_aeroo(docids, data=data) mimetype = self.MIMETYPES.get(rset[1], 'application/octet-stream') httpheaders = [('Content-Disposition', content_disposition(rset[2])), ('Content-Type', mimetype), ('Content-Length', len(rset[0]))] return request.make_response(rset[0], headers=httpheaders)
def report_routes(self, reportname, docids=None, converter=None, **data): # Trick the main reporter to think we want an HTML report new_converter = converter if converter != "xml" else "html" response = super(ReportController, self).report_routes(reportname, docids, new_converter, **data) # If it was an XML report, just download the generated response if converter == "xml": # XML header must be before any spaces, and it is a common error, # so let's fix that here and make developers happier response.data = response.data.strip() response.headers.set("Content-Type", "text/xml") response.headers.set('Content-length', len(response.data)) # set filename action_report_obj = request.env['ir.actions.report'] report = action_report_obj._get_report_from_name(reportname) filename = 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: filename = safe_eval(report.print_report_name, { 'object': records, 'time': time }) response.headers.set('Content-Disposition', content_disposition(filename + ".xml")) return response
def OAS_json_spec_download(self, namespace_name, **kwargs): ensure_db() namespace = http.request.env['openapi.namespace'].sudo().search([ ('name', '=', namespace_name) ]) if not namespace: raise werkzeug.exceptions.NotFound() if namespace.token != kwargs.get('token'): raise werkzeug.exceptions.Forbidden() response_params = {'headers': [('Content-Type', 'application/json')]} if 'download' in kwargs: response_params = { 'headers': [ ('Content-Type', 'application/octet-stream; charset=binary'), ('Content-Disposition', http.content_disposition('swagger.json')), ], 'direct_passthrough': True } return werkzeug.wrappers.Response(json.dumps(namespace.get_OAS()), status=200, **response_params)
def _show_report(self, model, report_type, report_ref, download=False): if report_type not in ('html', 'pdf', 'text'): raise UserError(_("Invalid report type: %s", report_type)) report_sudo = request.env.ref(report_ref).with_user(SUPERUSER_ID) if not isinstance(report_sudo, type(request.env['ir.actions.report'])): raise UserError( _("%s is not the reference of a report", report_ref)) if hasattr(model, 'company_id'): report_sudo = report_sudo.with_company(model.company_id) method_name = '_render_qweb_%s' % (report_type) report = getattr(report_sudo, method_name)([model.id], data={ 'report_type': report_type })[0] reporthttpheaders = [ ('Content-Type', 'application/pdf' if report_type == 'pdf' else 'text/html'), ('Content-Length', len(report)), ] if report_type == 'pdf' and download: filename = "%s.pdf" % (re.sub('\W+', '-', model._get_report_base_filename())) reporthttpheaders.append( ('Content-Disposition', content_disposition(filename))) return request.make_response(report, headers=reporthttpheaders)
def survey_get_certification(self, survey_id, **kwargs): """ The certification document can be downloaded as long as the user has succeeded the certification """ survey = request.env['survey.survey'].sudo().search([ ('id', '=', survey_id), ('certificate', '=', True) ]) if not survey: # no certification found return werkzeug.utils.redirect("/") succeeded_attempt = request.env['survey.user_input'].sudo().search( [('partner_id', '=', request.env.user.partner_id.id), ('survey_id', '=', survey_id), ('quizz_passed', '=', True)], limit=1) if not succeeded_attempt: raise UserError(_("The user has not succeeded the certification")) report_sudo = request.env.ref('survey.certification_report').sudo() report = report_sudo.render_qweb_pdf([succeeded_attempt.id], data={'report_type': 'pdf'})[0] reporthttpheaders = [ ('Content-Type', 'application/pdf'), ('Content-Length', len(report)), ] reporthttpheaders.append( ('Content-Disposition', content_disposition('Certification.pdf'))) return request.make_response(report, headers=reporthttpheaders)
def make_event_ics_file(self, event, **kwargs): if not event or not event.registration_ids: return request.not_found() files = event._get_ics_file() content = files[event.id] return request.make_response(content, [ ('Content-Type', 'application/octet-stream'), ('Content-Length', len(content)), ('Content-Disposition', content_disposition('%s.ics' % event.name)) ])
def _binary_set_headers(self, status, content, filename, mimetype, unique, filehash=None, download=False): headers = [('Content-Type', mimetype), ('X-Content-Type-Options', 'nosniff')] # cache etag = bool(request) and request.httprequest.headers.get('If-None-Match') status = status or (304 if filehash and etag == filehash else 200) if filehash: headers.append(('ETag', filehash)) headers.append(('Cache-Control', 'max-age=%s' % (STATIC_CACHE if unique else 0))) # content-disposition default name if download: headers.append(('Content-Disposition', content_disposition(filename))) return (status, headers, content)
def _show_report(self, model, report_type, report_ref, download=False): if report_type not in ('html', 'pdf', 'text'): raise UserError("Invalid report type: %s" % report_type) report_sudo = request.env.ref(report_ref).sudo() if not isinstance(report_sudo, type(request.env['ir.actions.report'])): raise UserError("%s is not the reference of a report" % report_ref) method_name = 'render_qweb_%s' % (report_type) report = getattr(report_sudo, method_name)([model.id], data={'report_type': report_type})[0] reporthttpheaders = [ ('Content-Type', 'application/pdf' if report_type == 'pdf' else 'text/html'), ('Content-Length', len(report)), ] if report_type == 'pdf' and download: filename = "%s.pdf" % (re.sub('\W+', '-', model._get_report_base_filename())) reporthttpheaders.append(('Content-Disposition', content_disposition(filename))) return request.make_response(report, headers=reporthttpheaders)
def portal_my_invoice_report(self, invoice_id, access_token=None, **kw): try: invoice_sudo = self._document_check_access('account.invoice', invoice_id, access_token) except (AccessError, MissingError): return request.redirect('/my') # print report as sudo, since it require access to taxes, payment term, ... and portal # does not have those access rights. accountInvoiceReport = request.env.ref('account.account_invoices').sudo() report_type = kw.get('report_type', 'pdf') method_name = 'render_qweb_%s' % (report_type) if hasattr(accountInvoiceReport, method_name): invoice_report = getattr(accountInvoiceReport, method_name)([invoice_sudo.id], data={'report_type': report_type})[0] reporthttpheaders = [ ('Content-Type', 'application/pdf' if report_type == 'pdf' else 'text/html'), ('Content-Length', len(invoice_report)), ] if report_type == 'pdf' and not kw.get('print'): filename = "%s.pdf" % (re.sub('\W+', '-', invoice_sudo._get_printed_report_name())) reporthttpheaders.append(('Content-Disposition', http.content_disposition(filename))) return request.make_response(invoice_report, headers=reporthttpheaders) raise NotFound()
def content_disposition(self, filename): return content_disposition(filename)
def content_disposition(cls, filename): return content_disposition(filename)