from odoo import api, fields, models from os.path import basename from zipfile import ZipFile from tempfile import TemporaryDirectory import base64 import os.path class IrAttachment(models.Model): _inherit = "ir.attachment" def download_massive_zip(self): self = self.with_user(1) zip_name = "Descarga masiva.zip" zip_file = self.env['ir.attachment'].sudo().search([('name', '=', zip_name)], limit=1) if zip_file: zip_file.sudo().unlink() # Funcion para decodificar el archivo def isBase64_decodestring(s): try: decode_archive = base64.decodebytes(s) return decode_archive except Exception as e: raise ValidationError('Error:', + str(e)) tempdir_file = TemporaryDirectory() location_tempdir = tempdir_file.name # Creando ruta dinamica para poder guardar el archivo zip date_act = fields.Date.today() file_name = 'DescargaMasiva(Fecha de descarga' + " - " + str(date_act) + ")" file_name_zip = file_name + ".zip" zipfilepath = os.path.join(location_tempdir, file_name_zip) path_files = os.path.join(location_tempdir) # Creando zip for file in self: object_name = file.name ruta_ob = object_name object_handle = open(os.path.join(location_tempdir, ruta_ob), "wb") object_handle.write(isBase64_decodestring(file.datas)) object_handle.close() with ZipFile(zipfilepath, 'w') as zip_obj: for file in os.listdir(path_files): file_path = os.path.join(path_files, file) if file_path != zipfilepath: zip_obj.write(file_path, basename(file_path)) with open(zipfilepath, 'rb') as file_data: bytes_content = file_data.read() encoded = base64.b64encode(bytes_content) data = { 'name': zip_name, 'type': 'binary', 'datas': encoded, 'company_id': self.env.company.id } attachment = self.env['ir.attachment'].sudo().create(data) self.unlink() return self.download_zip(file_name_zip, attachment.id) def download_zip(self, filename, id_file): path = "/web/binary/download_document?" model = "ir.attachment" url = path + "model={}&id={}&filename={}".format(model, id_file, filename) return { 'type': 'ir.actions.act_url', 'url': url, 'target': 'self', }