def download_attachment_pdf(self, model, id, method, attachment_id, auth_token, db, **kw): # FIXME use /web/binary/saveas directly dbname = db registry = RegistryManager.get(dbname) Model = registry.get('project.project') with registry.cursor() as cr: try: # find user via token u = registry.get('res.users') u_id = u.search(cr, openerp.SUPERUSER_ID, [('auth_token', '=', auth_token)]) res = getattr(Model, method)(cr, u_id[0], int(id), int(attachment_id)) if res: filecontent = base64.b64decode(res.get('base64')) filename = res.get('filename') content_type = mimetypes.guess_type(filename) if filecontent and filename: return request.make_response( filecontent, headers=[('Content-Type', content_type[0] or 'application/pdf'), ('Content-Disposition', content_disposition(filename).replace( "attachment;", "inline;"))] ) # open pdf files inline instead of downloading them except Exception, e: # signup error _logger.exception("OAuth2: %s" % str(e))
def save_as_attachment_ajax(self, req, data, token): jdata = simplejson.loads(data) model = jdata['model'] field = jdata['field'] data = None id = jdata.get('id', None) filename_field = jdata.get('filename_field', None) context = jdata.get('context', {}) Model = req.session.model(model) fields = [field] if filename_field: fields.append(filename_field) if data: res = {field: data} elif id: res = Model.read([int(id)], fields, context)[0] else: res = Model.default_get(fields, context) file_out = res.get(field, '') if not file_out: raise ValueError(_("No content found for field '%s' on '%s:%s'") % (field, model, id)) else: filename = '%s_%s' % (model.replace('.', '_'), id) if filename_field: filename = res.get(filename_field, '') or filename return req.make_response(file_out, headers=[('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename, req))], cookies={'fileToken': token})
def download_document(self, model, field, id, filename=None, **kw): """ Download link for files stored as binary fields. :param str model: name of the model to fetch the binary from :param str field: binary field :param str id: id of the record from which to fetch the binary :param str filename: field holding the file's name, if any :returns: :class:`werkzeug.wrappers.Response` """ Model = request.registry[model] cr, uid, context = request.cr, request.uid, request.context fields = [field] res = Model.read(cr, uid, [int(id)], fields, context)[0] filecontent = base64.b64decode(res.get(field) or '') if not filecontent: return request.not_found() else: if not filename: filename = '%s_%s' % (model.replace('.', '_'), id) return request.make_response( filecontent, [ ('Content-Disposition', content_disposition(filename)), # ('Content-Type', 'application/vnd.ms-excel'), ('Content-Type', 'application/octet-stream'), ('Content-Length', len(filecontent)) ])
def return_image(self, sku=None, **args): product_template = request.env['product.template'] product_template_ids = product_template.search([('sku', '=', sku)]) if not product_template_ids: result = request.not_found() elif len(product_template_ids.ids) > 1: result = request.not_found() else: image = product_template_ids.image if not image: result = request.not_found() else: image_type = 'jpg' try: tmp_filename = '/tmp/' + sku open(tmp_filename, 'wb').write(base64.b64decode(image)) image_type = imghdr.what(tmp_filename) os.remove(tmp_filename) except OSError: pass result = request.make_response( base64.b64decode(image), [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition('{}.{}'.format(sku, image_type)))]) return result
def download_attachment(self, **kw): """ Download link for files stored as binary fields. :param str model: name of the model to fetch the binary from :param str field: binary field :param str id: id of the record from which to fetch the binary :param str filename: field holding the file's name, if any :return: :class:`werkzeug.wrappers.Response` """ ir_attachment_domain = [('id', '=', int(kw['id']))] ir_attachment_obj = request.env['ir.attachment'] ir_attachment_set = ir_attachment_obj.search(ir_attachment_domain) filename = ir_attachment_set.datas_fname filecontent = base64.b64decode(ir_attachment_set.datas or '') if not filecontent: return request.not_found() return request.make_response(filecontent, \ [('Content-Type', ir_attachment_set.mimetype), \ ('Content-Disposition', content_disposition(filename))])
def index(self, action, token): result = super(Reports, self).index(action, token) action = simplejson.loads(action) context = dict(http.request.context) context.update(action["context"]) report_xml = http.request.session.model('ir.actions.report.xml') report_ids = report_xml.search( [('report_name', '=', action['report_name'])], 0, False, False, context=context) for report in report_xml.browse(report_ids): if not report.download_filename: continue # When you are on the form view of a customer and you # click on the "Sales" button, context['active_model'] # is still res.partner (probably a bug...) but # context['active_ids'] has the ID of the sale order # cf https://github.com/OCA/reporting-engine/issues/56 # That's why we use report.model instead of context['active_model'] # together with action['datas']['ids'] or context['active_ids'] objects = http.request.session.model(report.model)\ .browse(action.get('datas', {}).get( 'ids', context['active_ids'])) generated_filename = email_template.mako_template_env\ .from_string(report.download_filename)\ .render({ 'objects': objects, 'o': objects[0], 'object': objects[0], }) result.headers['Content-Disposition'] = main.content_disposition( generated_filename) return result
def labels_download(self, wizard_id): cr, uid, context = request.cr, request.uid, request.context wizard_model = request.registry['labelling.sheets.print.wizard'] wizard = wizard_model.browse(cr, uid, int(wizard_id), context=context) spec = wizard.spec_id.get_specification() template = wizard.content_template_id ids_str = wizard.object_ids obj_ids = map(int, ids_str.split(',')) if ids_str else [] objects = template.get_objects(obj_ids) pdf = template.get_pdf(spec, objects, print_options=wizard.get_print_options()) pdfhttpheaders = [ ('Content-Type', 'application/pdf'), ('Content-Length', len(pdf)), ('Content-Disposition', content_disposition("labels.pdf")), ] # This is to assist with debugging dump_dir = os.getenv('ODOO_LABELLING_DUMP_DIR') if dump_dir: dump_filepath = os.path.join(dump_dir, 'labels.pdf') with open(dump_filepath, 'wb') as df: df.write(pdf) _logger.info('Dumped labels to {}'.format(dump_filepath)) return request.make_response(pdf, headers=pdfhttpheaders)
def saveas(self, model, record_id, method, encoded=False, filename=None, **kw): """ Download link for files generated on the fly. :param str model: name of the model to fetch the data from :param str record_id: id of the record from which to fetch the data :param str method: name of the method used to fetch data, decorated with @api.one :param bool encoded: whether the data is encoded in base64 :param str filename: the file's name, if any :returns: :class:`werkzeug.wrappers.Response` """ Model = request.registry[model] cr, uid, context = request.cr, request.uid, request.context datas = getattr(Model, method)(cr, uid, int(record_id), context) if not datas: return request.not_found() filecontent = datas[0] if not filecontent: return request.not_found() if encoded: filecontent = base64.b64decode(filecontent) if not filename: filename = '%s_%s' % (model.replace('.', '_'), record_id) return request.make_response( filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def download_document(self, file, filename): if not file: return request.not_found() else: return request.make_response(file, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
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", content_disposition("swagger.json")), ], "direct_passthrough": True, } return werkzeug.wrappers.Response(json.dumps(namespace.get_OAS()), status=200, **response_params)
def index(self, **kw): filename = "abc.txt" # result = urllib.urlretrieve(url, "Customer.xlsx") filecontent = base64.b64decode(filename) return request.make_response( filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))]) # class DosSchedule(http.Controller): # @http.route('/dos_schedule/dos_schedule/', auth='public') # def index(self, **kw): # return "Hello World" # @http.route('/dos_schedule/dos_schedule/objects/', auth='public') # def list(self, **kw): # return http.request.render('dos_schedule.listing', { # 'root': '/dos_schedule/dos_schedule', # 'objects': http.request.env['dos_schedule.dos_schedule'].search([]), # }) # @http.route('/dos_schedule/dos_schedule/objects/<model("dos_schedule.dos_schedule"):obj>/', auth='public') # def object(self, obj, **kw): # return http.request.render('dos_schedule.object', { # 'object': obj # })
def base(self, data, token): params = simplejson.loads(data) model, fields, ids, domain, import_compat = \ operator.itemgetter('model', 'fields', 'ids', 'domain', 'import_compat')( params) Model = request.session.model(model) context = dict(request.context or {}, **params.get('context', {})) ids = ids or Model.search(domain, 0, False, False, context) field_names = map(operator.itemgetter('name'), fields) import_data = Model.new_export_data(ids, field_names, self.raw_data, context=context).get('datas', []) columns_headers = [val['label'].strip() for val in fields] return request.make_response( self.from_data(columns_headers, import_data), headers=[('Content-Disposition', content_disposition(self.filename(model))), ('Content-Type', self.content_type)], cookies={'fileToken': token})
def index(self, action, token): result = super(Reports, self).index(action, token) if result.status_code != 200: # In case of error don't change the response. return result action = json.loads(action) context = dict(http.request.context) context.update(action["context"]) report_xml = http.request.env['ir.actions.report.xml'] reports = report_xml.search([('report_name', '=', action['report_name']), ('download_filename', '!=', False)]) for report in reports: objects = http.request.session.model(context['active_model'])\ .browse(context['active_ids']) generated_filename = mail_template.mako_template_env\ .from_string(report.download_filename)\ .render({ 'objects': objects, 'o': objects[0], 'object': objects[0], }) result.headers['Content-Disposition'] = main.content_disposition( generated_filename) return result
def _file_report(self, action, token, context): report_srv = request.session.proxy("report") report_data, report_ids = self._get_report_data(context, action) report_struct = self._get_report_struct(action, report_data, report_ids, report_srv, context) report = base64.b64decode(report_struct['result']) if report_struct.get('code') == 'zlib': report = zlib.decompress(report) report_mimetype = self.TYPES_MAPPING.get(report_struct['format'], 'octet-stream') file_name = '%s.%s' % (self._get_file_name( action, context, report_ids), report_struct['format']) return request.make_response(report, headers=[ ('Content-Disposition', main.content_disposition(file_name)), ('Content-Type', report_mimetype), ('Content-Length', len(report)) ], cookies={'fileToken': token})
def ExportFormat_base(self, data, token): params = simplejson.loads(data) model, fields, ids, domain, import_compat = \ operator.itemgetter('model', 'fields', 'ids', 'domain', 'import_compat')( params) Model = request.session.model(model) context = dict(request.context or {}, **params.get('context', {})) ids = ids or Model.search(domain, context=context) if not request.env[model]._is_an_ordinary_table(): fields = [field for field in fields if field['name'] != 'id'] field_names = map(operator.itemgetter('name'), fields) import_data = Model.export_data(ids, field_names, self.raw_data, context=context).get('datas', []) if import_compat: columns_headers = field_names else: columns_headers = [val['label'].strip() for val in fields] return request.make_response(self.from_data(columns_headers, import_data), headers=[('Content-Disposition', content_disposition( self.filename(model))), ('Content-Type', self.content_type)], cookies={'fileToken': token})
def download_document(self,model,field,id,filename=None, **kw): """ Download link for files stored as binary fields. :param str model: name of the model to fetch the binary from :param str field: binary field :param str id: id of the record from which to fetch the binary :param str filename: field holding the file's name, if any :returns: :class:`werkzeug.wrappers.Response` """ Model = request.registry['labpal.experiment'] cr, uid, context = request.cr, request.uid, request.context fields = [field] res = Model.read(cr, uid, [int(id)], fields, context)[0] csv_file = StringIO() csv_writer = csv.writer(csv_file) csv_writer.writerow(["1","a","b","c"]) filecontent = base64.b64decode(csv_file) if not filecontent: return request.not_found() else: if not filename: filename = '%s_%s' % (model.replace('.', '_'), id) return request.make_response(filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def attachment_saveas(self, req, model, field, id=None, filename_field=None, **kw): Model = req.session.model(model) fields = ['datas'] if filename_field: fields.append(filename_field) if id: res = Model.read([int(id)], fields, req.context)[0] else: res = Model.default_get(fields, req.context) file_out = res.get('datas', '') if not file_out: return req.not_found() else: filename = '%s_%s' % (model.replace('.', '_'), id) if filename_field: filename = res.get(filename_field, '') or filename return req.make_response( file_out, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename, req))])
def download_document(self, tab_id, **kw): new_tab = ast.literal_eval(tab_id) attachment_ids = request.env['ir.attachment'].search([('id', 'in', new_tab)]) file_dict = {} for attachment_id in attachment_ids: file_store = attachment_id.store_fname if file_store: file_name = attachment_id.name file_path = attachment_id._full_path(file_store) file_dict["%s:%s" % (file_store, file_name)] = dict( path=file_path, name=file_name) zip_filename = datetime.now() zip_filename = "%s.zip" % zip_filename bitIO = BytesIO() zip_file = zipfile.ZipFile(bitIO, "w", zipfile.ZIP_DEFLATED) for file_info in file_dict.values(): zip_file.write(file_info["path"], file_info["name"]) zip_file.close() return request.make_response(bitIO.getvalue(), headers=[ ('Content-Type', 'application/x-zip-compressed'), ('Content-Disposition', content_disposition(zip_filename)) ])
def download_document(self, id, token, type, **post): signature_request = http.request.env['signature.request'].sudo( ).search([('id', '=', id), ('access_token', '=', token)]) if not signature_request: return http.request.not_found() document = None if type == "origin": document = signature_request.template_id.attachment_id.datas elif type == "completed": document = signature_request.completed_document if not document: return http.request.redirect( "/sign/document/%(request_id)s/%(access_token)s" % { 'request_id': id, 'access_token': token }) filename = signature_request.reference if filename != signature_request.template_id.attachment_id.datas_fname: filename += signature_request.template_id.attachment_id.datas_fname[ signature_request.template_id.attachment_id.datas_fname. rfind('.'):] return http.request.make_response( base64.b64decode(document), headers=[('Content-Type', mimetypes.guess_type(filename)[0] or 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def download_document(self, model, field, id, filename=None, **kw): """ Download link for files stored as binary fields. :param str model: name of the model to fetch the binary from :param str field: binary field :param str id: id of the record from which to fetch the binary :param str filename: field holding the file's name, if any :returns: :class:`werkzeug.wrappers.Response` """ Model = request.registry['labpal.experiment'] cr, uid, context = request.cr, request.uid, request.context fields = [field] res = Model.read(cr, uid, [int(id)], fields, context)[0] csv_file = StringIO() csv_writer = csv.writer(csv_file) csv_writer.writerow(["1", "a", "b", "c"]) filecontent = base64.b64decode(csv_file) if not filecontent: return request.not_found() else: if not filename: filename = '%s_%s' % (model.replace('.', '_'), id) return request.make_response( filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def get_companylogo(self, **kw): """ Provide static URL for company logo: "/web/image/companylogo" """ irModel = request.session.model('ir.attachment') dwa = request.session.model('dwa.fields') mod_obj = request.session.model('ir.model.data') # get logo and name from dwa by xml logo_ref = mod_obj.get_object_reference( 'epps_design', 'epps_dwa_fields_company_logo') logo_id = logo_ref and [logo_ref[1]] or False logo = dwa.browse(logo_id) if logo: irm = irModel.browse(logo.ir_att_id) # return Binary.image('ir.attachment', logo.ir_att_id, 'datas') if irm.exists(): print('irm') print(irm) print(irm.datas) image_data = irm.datas.decode('base64') imgname = 'logo.png' # image_data = StringIO(str(row[0]).decode('base64')) return request.make_response(image_data, headers=[ ('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(imgname)) ])
def download_document(self, model, field, id, filename=None, **kw): """ :param str filename: field holding the file's name, if any :returns: :class:`werkzeug.wrappers.Response` """ Model = request.registry[model] cr, uid, context = request.cr, request.uid, request.context fields = [field] res = Model.read(cr, uid, [int(id)], fields, context)[0] # filecontent = base64.b64decode(res.get(field) or '') filecontent = res.get(field) print(filecontent) if not filecontent: return request.not_found() else: if not filename: filename = '%s_%s' % (model.replace('.', '_'), id) headers = [ ('Content-Type', 'application/xml'), ('Content-Disposition', content_disposition(filename)), ('charset', 'utf-8'), ] return request.make_response(filecontent, headers=headers, cookies=None)
def download(self, id, format='xml', **kw): """ Download a mandat. Calls are made using the old api. This sucks. """ logger.debug('Download sepa mandat id:{0}'.format(id)) cr, uid, context = request.cr, request.uid, request.context sepa = request.registry['alkivi.sepa'].browse(cr, uid, int(id), context=context) date = datetime.datetime.strptime(sepa['date'], '%Y-%m-%d %H:%M:%S') if format == 'xml': filename = 'mandat_{0}.xml'.format(date.strftime('%Y_%m_%d')) logger.debug(filename) data = sepa.generate_xml() content_type = 'text/xml' if not data: return request.not_found() return request.make_response( data, [('Content-Type', content_type), ('Content-Disposition', content_disposition(filename))])
def report_routes(self, reportname, docids=None, converter=None, **data): response = super(ReportController, self).report_routes(reportname, docids=docids, converter=converter, **data) if docids: docids = [int(i) for i in docids.split(',')] report_xml = http.request.session.model('ir.actions.report.xml') report_ids = report_xml.search([('report_name', '=', reportname)]) for report in report_xml.browse(report_ids): if not report.download_filename: continue objects = http.request.session.model(report.model)\ .browse(docids or []) generated_filename = mail_template.mako_template_env\ .from_string(report.download_filename)\ .render({ 'objects': objects, 'o': objects[:1], 'object': objects[:1], 'ext': report.report_type.replace('qweb-', ''), }) response.headers['Content-Disposition'] = content_disposition( generated_filename) return response
def load_attendance_data(self): try: url = self.ethernet_url + "/iWsService" headers = {"content-type": "text/xml"} body = "<GetAttLog><ArgComKey xsi:type=\"xsd:integer\">" + \ "%s</ArgComKey>" % (self.key) + \ "<Arg><PIN xsi:type=\"xsd:integer\">All</PIN></Arg>" + \ "</GetAttLog>" response = requests.post(url, data=body, headers=headers) logger.info(response.content) root = ET.fromstring(response.content) with NamedTemporaryFile(mode="w+b") as f: attendance_writer = csv.writer(f, delimiter=",", quoting=csv.QUOTE_ALL) for elem in root.iter("Row"): str_pin = elem.find("PIN").text.encode("utf-8") str_datetime = elem.find("DateTime").text.encode("utf-8") str_status = elem.find("Status").text.encode("utf-8") attendance_writer.writerow( [str_pin, str_datetime, str_status]) f.seek(0) data = f.read() f.close() content = [("Content-Type", "text/csv;charset=utf-8"), ("Content-Disposition", oe_web.content_disposition("a.csv"))] return request.make_response(data, content) except Exception as e: logger.error('Error: %s' % str(e))
def download_documents(self, tab_id, rec_id, model_name, field_name, field_attach, **kw): new_tab = ast.literal_eval(tab_id) new_rec = ast.literal_eval(rec_id) attachment_ids = request.env['ir.attachment'].sudo().search([ ('id', 'in', new_tab) ]) rec_ids = request.env[model_name].sudo().search([('id', 'in', new_rec) ]) file_dict = {} for attachment_id in attachment_ids: for rec in rec_ids: if attachment_id in rec[field_attach]: file_store = attachment_id.store_fname if file_store: file_name = '{}/{}/{}'.format(rec.create_uid.login, rec[field_name], attachment_id.name) file_path = attachment_id._full_path(file_store) file_dict["%s:%s" % (file_name, file_path)] = dict( name=file_name, path=file_path) zip_filename = datetime.now() zip_filename = "%s.zip" % zip_filename bitIO = BytesIO() zip_file = zipfile.ZipFile(bitIO, "w", zipfile.ZIP_DEFLATED) for file_info in file_dict.values(): zip_file.write(file_info["path"], file_info["name"]) zip_file.close() return request.make_response(bitIO.getvalue(), headers=[ ('Content-Type', 'application/x-zip-compressed'), ('Content-Disposition', content_disposition(zip_filename)) ])
def download_outlook_add_in(self, debug=None): dir_path = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(dir_path, '..', 'bin', 'OutlookAddInInstaller.exe'), 'rb') as installer: # db = request.db # base_url = request.env['ir.config_parameter'].get_param('web.base.url') return request.make_response(installer.read(), [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition('OutlookAddInInstaller.exe'))])
def index(self, action, token): action = simplejson.loads(action) report_srv = request.session.proxy("report") context = dict(request.context) context.update(action["context"]) report_data = {} report_ids = context.get("active_ids", None) if 'report_type' in action: report_data['report_type'] = action['report_type'] if 'datas' in action: if 'ids' in action['datas']: report_ids = action['datas'].pop('ids') report_data.update(action['datas']) report_id = report_srv.report(request.session.db, request.session.uid, request.session.password, action["report_name"], report_ids, report_data, context) report_struct = None while True: report_struct = report_srv.report_get(request.session.db, request.session.uid, request.session.password, report_id) if report_struct["state"]: break time.sleep(self.POLLING_DELAY) report = base64.b64decode(report_struct['result']) if report_struct.get('code') == 'zlib': report = zlib.decompress(report) report_mimetype = self.TYPES_MAPPING.get(report_struct['format'], 'octet-stream') file_name = action.get('name', 'report') if 'name' not in action: reports = request.session.model('ir.actions.report.xml') res_id = reports.search([ ('report_name', '=', action['report_name']), ], 0, False, False, context) if len(res_id) > 0: file_name = reports.read(res_id[0], ['name'], context)['name'] else: file_name = action['report_name'] # Call hook to change filename file_name = get_file_name(file_name, action, context) file_name = '%s.%s' % (file_name, report_struct['format']) return request.make_response(report, headers=[('Content-Disposition', content_disposition(file_name)), ('Content-Type', report_mimetype), ('Content-Length', len(report))], cookies={'fileToken': token})
def attachment_saveas(self, model, field, id=None, filename_field=None, **kw): Model = request.session.model(model) filename, outfile = Model.get_attachment_file(int(id), request.context) if not outfile: return request.not_found() else: return request.make_response(outfile, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def download_temp_file(self, req, filename, token): location = config.get('zip_temp_file', '$HOME') file_out = file(location + '/' + filename, 'r') return req.make_response(file_out, headers=[('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(u'附件.zip', req))], cookies={'fileToken': token})
def download_vat_diary(self, debug=1, wizard_id=0, filename=''): # pragma: no cover """ Descarga un documento cuando se accede a la url especificada en http route. :param debug: Si esta o no en modo debug. :param int wizard_id: Id del modelo que contiene el documento. :param filename: Nombre del archivo. :returns: :class:`werkzeug.wrappers.Response`, descarga del archivo excel. """ filecontent = base64.b64decode(request.env['wizard.vat.diary'].browse(int(wizard_id)).report or '') return request.make_response(filecontent, [('Content-Type', 'application/excel'), ('Content-Disposition', content_disposition(filename))])
def download(self, name, **kw): try: file_to_download = open(name.replace("'", "/")) return http.request.make_response( file_to_download, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(name.split("'")[-1]))]) except Exception as e: print e
def export(self, module, format, **kwargs): filename = "{name}.{ext}".format(name=module.name, ext=format) fileIO = getattr(module, '_export_{format}'.format(format=format))() return request.make_response( fileIO.getvalue(), headers=[('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def download(self, module, **kwargs): filename = "{name}.{ext}".format(name=module.name, ext="zip") zfileIO = module.get_zipped_module() return request.make_response( zfileIO.getvalue(), headers=[('Content-Type', 'plain/text' or 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def download_attachment(self, req, model, id, method, attachment_id, **kw): Model = req.session.model(model) res = getattr(Model, method)(int(id), int(attachment_id)) if res: filecontent = base64.b64decode(res.get('base64')) filename = res.get('filename') if filecontent and filename: return req.make_response(filecontent, headers=[('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename, req))]) return req.not_found()
def report_download(self, data, token): """This function is used by 'qwebactionmanager.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 a filetoken cookie and an attachment header """ requestcontent = simplejson.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 docids: # Generic report: response = self.report_routes(reportname, docids=docids, converter='pdf') else: # Particular report: data = url_decode( url.split('?') [1]).items() # decoding the args represented in JSON response = self.report_routes(reportname, converter='pdf', **dict(data)) cr, uid = request.cr, request.uid report = request.registry['report']._get_report_from_name( cr, uid, reportname) filename = "%s.%s" % (report.name, "pdf") response.headers.add('Content-Disposition', content_disposition(filename)) response.set_cookie('fileToken', token) return response elif type == 'controller': reqheaders = Headers(request.httprequest.headers) response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True) response.set_cookie('fileToken', token) return response else: return except Exception, e: se = _serialize_exception(e) error = {'code': 200, 'message': "Odoo Server Error", 'data': se} return request.make_response(html_escape(simplejson.dumps(error)))
def pid_download_help(self): import os help_file_name = u'ПИД.pdf' with open(os.path.split(__file__)[0] + u'/' + help_file_name, 'rb') as f: doc_bytes = f.read() return http.request.make_response( doc_bytes, [('Content-Type', 'application/pdf'), ('Content-Disposition', content_disposition(help_file_name))])
def attachment_saveas_ajax(self, data, token): jdata = simplejson.loads(data) id = jdata.get('id', None) attachment_obj = request.session.model('ir.attachment') if id: filename, outfile = attachment_obj.get_attachment_file(int(id), request.context) return request.make_response(outfile, headers=[('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))], cookies={'fileToken': token}) else: raise ValueError(_("No attachment found for id '%s'") % id)
def report_download(self, data, token): """This function is used by 'qwebactionmanager.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 a filetoken cookie and an attachment header """ 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 docids: # Generic report: response = self.report_routes(reportname, docids=docids, converter='pdf') else: # Particular report: data = url_decode(url.split('?')[1]).items() # decoding the args represented in JSON response = self.report_routes(reportname, converter='pdf', **dict(data)) cr, uid = request.cr, request.uid report = request.registry['report']._get_report_from_name(cr, uid, reportname) filename = "%s.%s" % (report.name, "pdf") 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: filename = eval(report.print_report_name, {'object': obj, 'time': time}) response.headers.add('Content-Disposition', content_disposition(filename)) response.set_cookie('fileToken', token) return response elif type =='controller': reqheaders = Headers(request.httprequest.headers) response = Client(request.httprequest.app, BaseResponse).get(url, headers=reqheaders, follow_redirects=True) response.set_cookie('fileToken', token) return response else: return except Exception, e: se = _serialize_exception(e) error = { 'code': 200, 'message': "Odoo Server Error", 'data': se } return request.make_response(html_escape(json.dumps(error)))
def download_attachment(self, model, id, method, attachment_id, **kw): # FIXME use /web/binary/saveas directly Model = request.registry.get(model) res = getattr(Model, method)(request.cr, request.uid, int(id), int(attachment_id)) if res: filecontent = base64.b64decode(res.get('base64')) filename = res.get('filename') if filecontent and filename: return request.make_response( filecontent, headers=[('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))]) return request.not_found()
def export(self, exchanger, modules, **kwargs): exchanger = request.env[exchanger] modules = request.env['builder.ir.module.module'].search([ ('id', 'in', modules.split(',')) ]) filename = "{name}.{ext}".format(name=modules[0].name if len(modules) == 1 else 'modules', ext=exchanger.get_extension()) file_io = exchanger.get_exported_modules(modules) return request.make_response( file_io.getvalue(), headers=[('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def download_attachment(self, announcement, attachment): """ Route for download attachment """ if attachment.res_id == announcement.id: filecontent = base64.b64decode(attachment.datas) if not filecontent: response = request.not_found() else: filename = attachment.name response = request.make_response(filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))]) else: response = request.not_found() return response
def download(self, generator, modules, **kwargs): generator = request.env[generator] modules = request.env['builder.ir.module.module'].search([ ('id', 'in', modules.split(',')) ]) filename = "{name}.{ext}".format(name=modules[0].name if len(modules) == 1 else 'modules', ext="zip") zip_io = generator.get_zipped_modules(modules) return request.make_response( zip_io.getvalue(), headers=[ ('Content-Type', 'plain/text' or 'application/octet-stream'), ('Content-Disposition', content_disposition(filename)) ] )
def download_attachment(self, model, id, method, attachment_id, **kw): # FIXME use /web/binary/saveas directly Model = request.registry.get(model) res = getattr(Model, method)(request.cr, request.uid, int(id), int(attachment_id)) if res: filecontent = base64.b64decode(res.get("base64")) filename = res.get("filename") content_type = mimetypes.guess_type(filename) if filecontent and filename: return request.make_response( filecontent, headers=[ ("Content-Type", content_type[0] or "application/octet-stream"), ("Content-Disposition", content_disposition(filename)), ], ) return request.not_found()
def report_download(self, data, token): """This function is used by 'qwebactionmanager.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 a filetoken cookie and an attachment header """ 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 docids: # Generic report: response = self.report_routes(reportname, docids=docids, converter="pdf") else: # Particular report: data = url_decode(url.split("?")[1]).items() # decoding the args represented in JSON response = self.report_routes(reportname, converter="pdf", **dict(data)) cr, uid = request.cr, request.uid report = request.registry["report"]._get_report_from_name(cr, uid, reportname) filename = "%s.%s" % (report.name, "pdf") response.headers.add("Content-Disposition", content_disposition(filename)) response.set_cookie("fileToken", token) return response elif type == "controller": reqheaders = Headers(request.httprequest.headers) response = Client(request.httprequest.app, BaseResponse).get( url, headers=reqheaders, follow_redirects=True ) response.set_cookie("fileToken", token) return response else: return except Exception, e: se = _serialize_exception(e) error = {"code": 200, "message": "Odoo Server Error", "data": se} return request.make_response(html_escape(json.dumps(error)))
def attachment_saveas(self, req, model, field, id=None, filename_field=None, **kw): Model = req.session.model(model) fields = ['datas'] if filename_field: fields.append(filename_field) if id: res = Model.read([int(id)], fields, req.context)[0] else: res = Model.default_get(fields, req.context) file_out = res.get('datas', '') if not file_out: return req.not_found() else: filename = '%s_%s' % (model.replace('.', '_'), id) if filename_field: filename = res.get(filename_field, '') or filename return req.make_response(file_out, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename, req))])
def download_document(self, model, field, ids, filename=None, **kw): """ Download link for files stored as binary fields. :param str model: name of the model to fetch the binary from :param str field: binary field :param str id: id of the record from which to fetch the binary :param str filename: field holding the file's name, if any :returns: :class:`werkzeug.wrappers.Response` """ Model = request.registry[model] cr, uid, context = request.cr, request.uid, request.context fields = [field] # res = Model.read(cr, uid, ids, ['rollno', 'length', 'weight'], context)[0] print ids # tids = [int(s) for s in ids] # print tids list_str = [] for s in ids: list_str.append(s) print ids.split(',') # res = Model.read(cr, uid, ids, ['rollno', 'length', 'weight'], context)[0] res = Model.search(cr, uid, [('id', 'in', ids.split(','))], context) # self.search(cr, uid, [('state', '=', 'inprogress')], context=context) print res print field print res.get("rollno") print '123123' # filecontent = base64.b64decode(res.get("rollno") or '') filecontent = res.get("rollno") print 'zzzzzzzzzzzzzz' print filecontent if not filecontent: print 'aasssssssssssssssssssss' return request.not_found() else: if not filename: filename = '%s_%s' % (model.replace('.', '_'), ids.replace(',', '-')) return request.make_response(filecontent, [('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename))])
def saveas_ajax(self, req, data, token): jdata = simplejson.loads(data) model = jdata['model'] field = jdata['field'] data = jdata['data'] id = jdata.get('id', None) filename_field = jdata.get('filename_field', None) context = jdata.get('context', {}) Model = req.session.model(model) fields = [field] if filename_field: fields.append(filename_field) if data: res = { field: data } #add the file name getting by johnw, 06/27/2014 #begin if filename_field: res_filename = {} if id: res_filename = Model.read(int(id), [filename_field], context) else: res_filename = Model.default_get([filename_field], context) if len(res_filename) > 0: res.update({filename_field:res_filename[filename_field]}) #end elif id: res = Model.read([int(id)], fields, context)[0] else: res = Model.default_get(fields, context) filecontent = base64.b64decode(res.get(field, '')) if not filecontent: raise ValueError(_("No content found for field '%s' on '%s:%s'") % (field, model, id)) else: filename = '%s_%s' % (model.replace('.', '_'), id) if filename_field: filename = res.get(filename_field, '') or filename return req.make_response(filecontent, headers=[('Content-Type', 'application/octet-stream'), ('Content-Disposition', content_disposition(filename, req))], cookies={'fileToken': token})
def download_attachment(self, model, id, method, attachment_id, downloadall=False, **kw): if downloadall: message_id = request.registry.get('mail.message').browse(request.cr, request.session.uid, [int(id)], {}) if message_id.parent_id: zip_subdir = message_id.parent_id.subject or 'attachment' else: zip_subdir = message_id.subject or 'attachment' filenames = [] for attachment_id in message_id.attachment_ids: Model = request.registry.get(model) res = getattr(Model, method)(request.cr, request.uid, int(id), int(attachment_id)) if res: filecontent = base64.b64decode(res.get('base64')) filename = res.get('filename') content_type = mimetypes.guess_type(filename) attachment_file = open(str("/tmp/%s" % filename), "wb") attachment_file.write(filecontent) filenames.append('/tmp/%s'%filename) zip_filename = "%s.zip" % zip_subdir.replace(" ", "").lower() strIO = StringIO.StringIO() zip_file = zipfile.ZipFile(strIO, "w", zipfile.ZIP_DEFLATED) for file_path in filenames: file_dir, file_name = os.path.split(str(file_path)) zip_path = os.path.join(zip_subdir, file_name) zip_file.write(file_path, zip_path) zip_file.close() return request.make_response( strIO.getvalue(), headers=[('Content-Type', 'application/x-zip-compressed'), ('Content-Disposition', content_disposition(zip_filename))]) else: return super(MailController, self).download_attachment(model, id, method, attachment_id)
def esl_download(self, id): try: ESLWizard = request.registry['account.vat.esl'] esl = ESLWizard.browse(request.cr, request.uid, int(id)) if esl: filecontent = esl.esl_csv_data() period_name = esl.period_from.name filename = 'esl_%s.csv' % (period_name,) return request.make_response( filecontent, headers=[ ('Content-Type', 'text/csv'), ('Content-Disposition', content_disposition(filename)), ], ) else: return request.not_found() except Exception, e: error = { 'code': 200, 'message': 'Odoo Server Error', 'data': _serialize_exception(e), } return request.make_response(html_escape(simplejson.dumps(error)))
def index(self, action, token): result = super(Reports, self).index(action, token) action = simplejson.loads(action) context = dict(http.request.context) context.update(action["context"]) report_xml = http.request.session.model('ir.actions.report.xml') report_ids = report_xml.search( [('report_name', '=', action['report_name'])], 0, False, False, context=context) for report in report_xml.browse(report_ids): if not report.download_filename: continue objects = http.request.session.model(context['active_model'])\ .browse(context['active_ids']) generated_filename = email_template.mako_template_env\ .from_string(report.download_filename)\ .render({ 'objects': objects, 'o': objects[0], 'object': objects[0], }) result.headers['Content-Disposition'] = main.content_disposition( generated_filename) return result
def report_routes(self, reportname, docids=None, converter=None, **data): response = super(ReportController, self).report_routes( reportname, docids=docids, converter=converter, **data) if docids: docids = [int(i) for i in docids.split(',')] report_xml = http.request.session.model('ir.actions.report.xml') report_ids = report_xml.search( [('report_name', '=', reportname)]) for report in report_xml.browse(report_ids): if not report.download_filename: continue objects = http.request.session.model(report.model)\ .browse(docids or []) generated_filename = email_template.mako_template_env\ .from_string(report.download_filename)\ .render({ 'objects': objects, 'o': objects[:1], 'object': objects[:1], 'ext': report.report_type.replace('qweb-', ''), }) response.headers['Content-Disposition'] = content_disposition( generated_filename) return response
def download_document(self, model, field, id, filename=None, **kw): print("----------------- download_document ------------------") partner_id = id wizard_obj = request.registry["mail.mass_export_partner"] wizards = wizard_obj.read(request.cr, request.uid, [int(partner_id)], ["partner_ids"], context=None) wizard = wizards[0] partner_ids = wizard["partner_ids"] print("----") print(partner_ids) Model = request.registry[model] activities_obj = request.registry["sead.activity.child"] partner_obj = request.registry["res.partner"] # los ejecutivos partners = partner_obj.read( request.cr, request.uid, partner_ids, [ "is_company", "name", "names", "last_name", "gender_suffix", "title", "email", "email_exclude", "email_gracias", "hierarchy_level", ], context=None, ) # cabeceras fc = "" for partner in partners: if partner["is_company"] == False: name = partner["name"] if partner["name"] else "" names = partner["names"] if partner["names"] else "" last_name = partner["last_name"] if partner["last_name"] else "" suffix = partner["gender_suffix"] if partner["gender_suffix"] else "o" estimado = "Estimad" + suffix nivel = prep_csv(partner["hierarchy_level"] if partner["hierarchy_level"] else "") title = partner["title"][1] if partner["title"] else "" email = "" if ( (partner["email_exclude"] == False) and (partner["email_gracias"] == False) and (partner["email"] != False) ): email = partner["email"] fc = ( fc + prep_csv(email) + "," + prep_csv(estimado) + "," + prep_csv(title) + "," + prep_csv(names) + "," + prep_csv(last_name) + "," + prep_csv(suffix) + "," + prep_csv(email) + "," ) fc = fc + nivel + "," + prep_csv(name) + "\n" if not fc: print("not fc") return request.not_found() else: print(" si fc") print(filename) if not filename: print("not filename") filename = "%s_%s" % (model.replace(".", "_"), id) return request.make_response( fc, # [('Content-Type', 'application/octet-stream'),('Content-Disposition', content_disposition(filename))]) [ ("Content-Type", "application/octet-stream;charset=utf-8"), ("Content-Disposition", content_disposition(filename)), ], )
def download_document(self, model, field, id, filename=None, **kw): partner_id = id partner_obj = request.registry["res.partner"] partners = partner_obj.read( request.cr, request.uid, [int(partner_id)], ["name", "vat", "common_name", "activities", "child_ids"], context=None, ) partner = partners[0] Model = request.registry[model] # cabeceras fc = "" fc = fc + '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' + "\n" fc = fc + "<html>" + "\n" fc = fc + "<head>" + "\n" # fc = fc + ' <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">' + '\n' fc = fc + ' <meta http-equiv="content-type" content="text/html; charset=utf-8"/>' + "\n" fc = fc + " <title>Ficha de empresa</title>" + "\n" fc = fc + "</head>" + "\n" fc = fc + "<body>" + "\n" # la empresa if partner["vat"]: empr_ruc = partner["vat"] else: empr_ruc = "" if partner["common_name"]: empr_common_name = partner["common_name"] else: empr_common_name = "" fc = fc + ' <big><span style="font-weight: bold;">' + partner["name"] + "</span></big>" + "\n" fc = fc + ' <small><br style="font-family: Helvetica,Arial,sans-serif;">RUC: ' + empr_ruc + "\n" fc = fc + ' <br style="font-family: Helvetica,Arial,sans-serif;">Nombre comun: ' + empr_common_name + "\n" fc = fc + ' <br style="font-family: Helvetica,Arial,sans-serif;">Actividades:' + "\n" activities_obj = request.registry["sead.activity.child"] activities = activities_obj.read(request.cr, request.uid, partner["activities"], ["name"], context=None) for activity in activities: fc = fc + '<br style="font-family: Helvetica,Arial,sans-serif;">' + activity["name"] + "<br>" + "\n" fc = fc + "<br></small>" # los ejecutivos childs = partner_obj.read( request.cr, request.uid, partner["child_ids"], [ "name", "vat", "function", "business_area", "hierarchy_level", "street", "email", "direct_phone", "secretary", "semi_fecha_modificacion", "state_id", "province_id", "district_id", "gender_suffix", ], context=None, ) Ordenar_Lista(childs, "hierarchy_level", "A") for child in childs: cargo_email = child["email"] if child["email"] else "" cargo_direct_phone = child["direct_phone"] if child["direct_phone"] else "" cargo_secretaria = child["secretary"] if child["secretary"] else "" cargo_cargo = child["function"] if child["function"] else "" cargo_area = child["business_area"][1] if child["business_area"] else "" cargo_nivel = child["hierarchy_level"] if child["hierarchy_level"] else "" cargo_modif = child["semi_fecha_modificacion"] if child["semi_fecha_modificacion"] else "" state = child["state_id"][1] if child["state_id"] else "" province = child["province_id"][1] if child["province_id"] else "" district = child["district_id"][1] if child["district_id"] else "" td_start = '<td style="font-family: Helvetica,Arial,sans-serif;"><small>' td_close = "</small></td>" fc = fc + ' <hr style="width: 100%; height: 2px;">' + "\n" fc = ( fc + ' <table style="text-align: left; width: 100%;" border="0" cellpadding="0" cellspacing="2">' + "\n" ) fc = fc + " <tbody>" + "\n" fc = fc + " <tr>" + "\n" fc = fc + " " + td_start + "Cargo: " + cargo_cargo + td_close + "\n" # fc = fc + ' ' + td_start + 'Nombre: ' + child['name'].decode('utf-8') + td_close + '\n' fc = fc + " " + td_start + "Nombre: " + child["name"] + td_close + "\n" fc = fc + " </tr>" + "\n" fc = fc + " <tr>" + "\n" fc = fc + " " + td_start + "Area: " + cargo_area + td_close + "\n" fc = fc + " " + td_start + "Nivel: " + cargo_nivel + td_close + "\n" fc = fc + " </tr>" + "\n" fc = fc + " <tr>" + "\n" fc = fc + " " + td_start + "Direccion: " + child["street"] + td_close + "\n" fc = fc + " " + td_start + state + " / " + province + " / " + district + td_close + "\n" fc = fc + " </tr>" + "\n" fc = fc + " <tr>" + "\n" fc = fc + " " + td_start + "eMail: " + cargo_email + td_close + "\n" fc = fc + " " + td_start + "Telefono directo: " + cargo_direct_phone + td_close + "\n" fc = fc + " </tr>" + "\n" fc = fc + " <tr>" + "\n" fc = fc + " " + td_start + "Secretaria: " + cargo_secretaria + td_close + "\n" fc = fc + " " + td_start + td_close + "\n" fc = fc + " </tr>" + "\n" fc = fc + " <tr>" + "\n" fc = fc + " " + td_start + "Ultima actualizacion: " + cargo_modif + td_close + "\n" fc = fc + " " + td_start + "</td>" + "\n" fc = fc + " </tr>" + "\n" fc = fc + " </tbody>" + "\n" fc = fc + " </table>" + "\n" fc = fc + " <br>" + "\n" fc = fc + "</body></html>" if not fc: print("not fc") return request.not_found() else: print(" si fc") print(filename) if not filename: print("not filename") filename = "%s_%s" % (model.replace(".", "_"), id) return request.make_response( fc, [("Content-Type", "application/octet-stream"), ("Content-Disposition", content_disposition(filename))], )
file_name = new_file_name if len(context['active_ids']) == 1: model_rec_name = model_obj.name_get(context['active_ids'],context)[0][1] if model_rec_name: #johnw, if the get_report_name returned full name then no need to add object name if not file_name.endswith(report_struct['format']): file_name = '%s_%s' % (file_name, model_rec_name) except Exception: pass #johnw, if the get_report_name returned full name then no need to add extension if not file_name.endswith(report_struct['format']): file_name = '%s.%s' % (file_name, report_struct['format']) return req.make_response(report, headers=[ ('Content-Disposition', content_disposition(file_name, req)), ('Content-Type', report_mimetype), ('Content-Length', len(report))], cookies={'fileToken': token}) WebReports.index = metro_rpt_index ''' Fix the download file name issue ''' from openerp.addons.web.controllers.main import Binary as WebBinary @httprequest def saveas_ajax(self, req, data, token): jdata = simplejson.loads(data) model = jdata['model']
def download_document(self,model,field,id,filename=None, **kw): print('----------------- download_document ------------------') registration_id = id wizard_obj = request.registry['event.export_registration'] wizards = wizard_obj.read(request.cr, request.uid, [int(registration_id)], ['registration_ids'], context=None) wizard = wizards[0] registration_ids = wizard['registration_ids'] print('----') print(registration_ids) Model = request.registry[model] # vamos a jalar los registros registration_obj = request.registry['event.registration'] registrations = registration_obj.read(request.cr, request.uid, registration_ids, ['id', 'name', 'display_name', 'partner_id', 'partner_function', 'credential_printed', 'state'], context=None) # iniciemos un objeto partner para busquedas partner_obj = request.registry['res.partner'] # cabeceras fc = '' for registration in registrations: if (not (registration['credential_printed'])) and (registration['state'] != 'cancel'): # si el partner_id corresponde a un ejecutivo, podemos extraer sus nombres y apellidos partner = partner_obj.read(request.cr, request.uid, registration['partner_id'][0], ['is_company', 'name', 'names', 'last_name', 'mother_name', 'gender_suffix', 'title', 'parent_id'], context=None) if partner['is_company']: # no tenemos un ejecutivo en la BD, solamente lo escrito en el registro names = registration['name'] if registration['name'] else "" apellido_p = '' apellido_m = '' cargo = registration['partner_function'] if registration['partner_function'] else "" company = partner['name'] else: # es un ejecutivo de la BD, tenemos sus datos desagregados names = partner['names'] if partner['names'] else "" apellido_p = partner['last_name'] if partner['last_name'] else "" apellido_m = partner['mother_name'] if partner['mother_name'] else "" cargo = registration['partner_function'] if registration['partner_function'] else "" company = partner['parent_id'][1] fc = fc + prep_barras(names) + prep_barras(apellido_p) + prep_barras(apellido_m) + prep_barras(cargo) + prep_barras(company) + '\n' if not fc: print('not fc') return request.not_found() else: print(' si fc') print(filename) if not filename: print('not filename') filename = '%s_%s' % (model.replace('.', '_'), id) return request.make_response(fc, #[('Content-Type', 'application/octet-stream'),('Content-Disposition', content_disposition(filename))]) [('Content-Type', 'application/octet-stream;charset=utf-8'),('Content-Disposition', content_disposition(filename))])
def download_document(self, model, field, id, filename=None, **kw): print("----------------- download_document ------------------") partner_id = id wizard_obj = request.registry["mail.mass_mailing.wizard"] wizards = wizard_obj.read( request.cr, request.uid, [int(partner_id)], ["partner_ids", "mailing_id"], context=None ) wizard = wizards[0] partner_ids = wizard["partner_ids"] print("----") print(partner_ids) Model = request.registry[model] partner_obj = request.registry["res.partner"] # los ejecutivos partners = partner_obj.read( request.cr, request.uid, partner_ids, ["is_company", "name", "street", "state_id", "province_id", "district_id"], context=None, ) # cabeceras fc = "" for partner in partners: if partner["is_company"] == False: name = partner["name"] if partner["name"] else "" street = partner["street"] if partner["street"] else "" state = partner["state_id"][1] if partner["state_id"] else "" province = partner["province_id"][1] if partner["province_id"] else "" district = partner["district_id"][1] if partner["district_id"] else "" fc = ( fc + prep_csv(name) + "," + prep_csv(street) + "," + prep_csv(district) + "," + prep_csv(province) + "," + prep_csv(state) + "\n" ) # test = 'Ramírez' # udata = test.decode("utf-8") # asciidata = udata.encode("ascii","ignore") # ANSI ??????? # fc = udata if not fc: print("not fc") return request.not_found() else: print(" si fc") print(filename) if not filename: print("not filename") filename = "%s_%s" % (model.replace(".", "_"), id) return request.make_response( fc, # [('Content-Type', 'application/octet-stream'),('Content-Disposition', content_disposition(filename))]) [ ("Content-Type", "application/octet-stream;charset=utf-8"), ("Content-Disposition", content_disposition(filename)), ], )
def download_document(self, model, field, id, filename=None, **kw): print("----------------- download_document ------------------") partner_id = id wizard_obj = request.registry["mail.mass_export_partner"] wizards = wizard_obj.read(request.cr, request.uid, [int(partner_id)], ["partner_ids"], context=None) wizard = wizards[0] partner_ids = wizard["partner_ids"] print("----") print(partner_ids) Model = request.registry[model] activities_obj = request.registry["sead.activity.child"] partner_obj = request.registry["res.partner"] # los ejecutivos partners = partner_obj.read( request.cr, request.uid, partner_ids, [ "is_company", "name", "names", "last_name", "gender_suffix", "title", "email", "email_exclude", "email_gracias", "personal_email", "personal_email_exclude", "personal_email_gracias", "secretary_email", "secretary_email_exclude", "secretary_email_gracias", "secretary_personal_email", "secretary_personal_email_exclude", "secretary_personal_email_gracias", "hierarchy_level", "function", "business_area", "activities", "parent_id", ], context=None, ) # cabeceras fc = "" for partner in partners: if partner["is_company"] == False: name = partner["name"] if partner["name"] else "" names = partner["names"] if partner["names"] else "" last_name = partner["last_name"] if partner["last_name"] else "" suffix = partner["gender_suffix"] if partner["gender_suffix"] else "o" estimado = "Estimad" + suffix nivel = prep_csv(partner["hierarchy_level"] if partner["hierarchy_level"] else "") cargo = prep_csv(partner["function"] if partner["function"] else "") area = prep_csv(partner["business_area"][1] if partner["business_area"] else "") title = partner["title"][1] if partner["title"] else "" empresa = partner["parent_id"][1] if partner["parent_id"] else "" actividades = "" for actividad_id in partner["activities"]: act = activities_obj.read(request.cr, request.uid, actividad_id, ["name"], context=None) if actividades != "": actividades = actividades + " - " actividades = actividades + act["name"] emails = [] if ( (partner["email_exclude"] == False) and (partner["email_gracias"] == False) and (partner["email"] != False) ): emails = emails + [partner["email"]] if ( (partner["personal_email_exclude"] == False) and (partner["personal_email_gracias"] == False) and (partner["personal_email"] != False) ): emails = emails + [partner["personal_email"]] if ( (partner["secretary_email_exclude"] == False) and (partner["secretary_email_gracias"] == False) and (partner["secretary_email"] != False) ): emails = emails + [partner["secretary_email"]] if ( (partner["secretary_personal_email_exclude"] == False) and (partner["secretary_personal_email_gracias"] == False) and (partner["secretary_personal_email"] != False) ): emails = emails + [partner["secretary_personal_email"]] emails_text = "" for email in emails: if len(emails_text) == 0: emails_text = emails_text + email else: emails_text = emails_text + ";" + email email = "" if len(emails) > 0: email = emails[0] fc = ( fc + prep_csv(email) + "," + prep_csv(estimado) + "," + prep_csv(title) + "," + prep_csv(names) + "," + prep_csv(last_name) + "," + prep_csv(suffix) + "," + prep_csv(emails_text) + "," ) fc = ( fc + cargo + "," + area + "," + nivel + "," + prep_csv(name) + "," + prep_csv(empresa) + "," + prep_csv(actividades) + "\n" ) if not fc: print("not fc") return request.not_found() else: print(" si fc") print(filename) if not filename: print("not filename") filename = "%s_%s" % (model.replace(".", "_"), id) return request.make_response( fc, # [('Content-Type', 'application/octet-stream'),('Content-Disposition', content_disposition(filename))]) [ ("Content-Type", "application/octet-stream;charset=utf-8"), ("Content-Disposition", content_disposition(filename)), ], )
def download_document(self, model, field, id, filename=None, **kw): print("----------------- download_document ------------------") partner_id = id wizard_obj = request.registry["mail.mass_export_partner"] wizards = wizard_obj.read(request.cr, request.uid, [int(partner_id)], ["partner_ids"], context=None) wizard = wizards[0] partner_ids = wizard["partner_ids"] print("----") print(partner_ids) Model = request.registry[model] partner_obj = request.registry["res.partner"] # los ejecutivos partners = partner_obj.read( request.cr, request.uid, partner_ids, [ "is_company", "name", "names", "last_name", "mother_name", "gender", "gender_suffix", "title", "function", "street", "state_id", "province_id", "district_id", "parent_id", ], context=None, ) # cabeceras fc = "" for partner in partners: if partner["is_company"] == False: name = partner["name"] if partner["name"] else "" names = partner["names"] if partner["names"] else "" last_name = partner["last_name"] if partner["last_name"] else "" mother_name = partner["mother_name"] if partner["mother_name"] else "" function = partner["function"] if partner["function"] else "" suffix = partner["gender_suffix"] if partner["gender_suffix"] else "o" gender = partner["gender"] if partner["gender"] else "" estimado = "Estimad" + suffix title = partner["title"][1] if partner["title"] else "" street = partner["street"] if partner["street"] else "" state = partner["state_id"][1] if partner["state_id"] else "" province = partner["province_id"][1] if partner["province_id"] else "" district = partner["district_id"][1] if partner["district_id"] else "" empresa = partner["parent_id"][1] if partner["parent_id"] else "" fc = ( fc + prep_csv(empresa) + "," + prep_csv(names) + "," + prep_csv(last_name) + "," + prep_csv(mother_name) + "," + prep_csv(function) + "," + prep_csv(street) + "," + prep_csv(district) + "," + prep_csv(province) + "," + prep_csv(state) + "," + prep_csv(estimado) + "," + prep_csv(name) + "," + prep_csv(title) + "," + prep_csv(suffix) + "\n" ) if not fc: print("not fc") return request.not_found() else: print(" si fc") print(filename) if not filename: print("not filename") filename = "%s_%s" % (model.replace(".", "_"), id) return request.make_response( fc, # [('Content-Type', 'application/octet-stream'),('Content-Disposition', content_disposition(filename))]) [ ("Content-Type", "application/octet-stream;charset=utf-8"), ("Content-Disposition", content_disposition(filename)), ], )