Odoo 12. 如何将二进制文件转换为 Zip?

Odoo 12. How to convert Binary File to Zip?

我需要导入一个仅包含 xml 个文件的 zip 文件。

我的向导看起来像这样:

class ZipImportsWizard(models.Model):
    _name = 'import.zip.dte'

    type = fields.Selection([('purchase', 'Purchases'),('sale', 'Sales'),], string="Type", default="purchase")
    file = fields.Binary(string='ZIP File', store=True)

我需要打开这个 zip 文件并检查内容。 如果内容没问题,我只好把这个发到别的方法了。

问题是,当我上传文件时,它会转换为二进制文件,所以我无法使用 zipfile 库来处理它。

如何再次将此二进制文件转换为 Zip 文件以使用它?

我没有用过odoo;但是:

如果 你有一个字节变量(二进制数据),你可以使用 io.BytesIO and zipfile 使用标准 python 库将其作为 Zipfile 读取:

from io import BytesIO
import zipfile

 # I assume ths contains the zipfile uploaded by the user.
 uploaded_zipfile = fields.Binary(string='ZIP File', store=True)

with BytesIO(uploaded_zipfile) as fp:
   userzip = zipfile.ZipFile(fp, 'r')

   # You can extract the zip like this:
   userzip.extractall()

   # Or you can check the contents without extracting all the file
   whats_inside_the_zip = userzip.infolist()


我能够自己找到解决方案,但也要感谢@astronautlevel 的回答Similar question

from odoo import fields, models, _
from odoo.exceptions import UserError, ValidationError
import zipfile
import tempfile

class ZipImportsWizard(models.Model):
    _name = 'import.zip.dte'

    type = fields.Selection([('purchase', 'Purchases'),('sale', 'Sales'),], string="Type", default="purchase")
    file = fields.Binary(string='ZIP File', store=True)
    file_name = fields.Char('File name')

    def read_files_from_zip(self):
        file = base64.decodestring(self.zip_file)
        fobj = tempfile.NamedTemporaryFile(delete=False)
        fname = fobj.name
        fobj.write(file)
        fobj.close()

        zipzip = self.zip_file
        f = open(fname, 'r+b')  
        data = f.read()
        f.write(base64.b64decode(zipzip))
        pos = data.find(b'\x50\x4b\x05\x06')
        f.seek(pos + 22)
        with zipfile.ZipFile(f, 'r') as zip_file: 
            # do some stuff
            
            f.close()

        return