python - 将 odoo 图像存储到文件系统中

标签 python odoo odoo-11

希望所有堆栈成员都没事。我能够使用代码获取产品图像的二进制数据

p_ids=self.env.context.get('active_ids')
produtc_templates = self.env['product.template']
for p_id in p_ids:
 binaryData = produtc_templates.search([('id', '=',p_id)]).image 
 data=base64.b64decode(binaryData)
        file="marketplaces/rakuten_ftp/static/imageToSave_"+str(p_id)+".png"
        with open(file, "wb") as imgFile:
            imgFile.write(data)

上面的代码是从二进制数据创建文件,但我无法在 mimetype 基础上应用条件。因为当我使用产品 id 查询 ir_attachment 表时,它返回 False。

for p_id in p_ids:
 attachments = self.env['ir.attachment']
 mimetype=attachments.search([('res_id','=',p_id)])

我正在考虑将 res_id 作为产品 id。但是 odoo 未能找到针对该 id 的任何记录。因此,如果有人知道如何根据我的产品 id 获取 mimetype,请帮助我。

最佳答案

你的代码看起来不错!但根据 ir.attachment 对象,二进制数据存储在 datas 字段中。因此,您可以使用该数据将二进制数据解码为图像文件!!

已经在Odoo v11中尝试了以下代码...并且它正在根据存储在datas字段中的二进制数据创建新的图像文件!

product_image = self.env['ir.attachment']
product_images = product_image.search([('id', 'in', p_ids)])
for rec in product_images:
    with open("imageToSave.jpg", "wb") as imgFile:
        imgFile.write(base64.b64decode(rec.datas))

您还可以添加 mimetype 条件,因为 p_ids 可以包含多个 id,因此仅采用 mimetypeimage/jpegimage/png

编辑#1

下面的代码片段已使用 Odoo v11.0 检查

import base64
from odoo.tools.mimetypes import guess_mimetype


p_ids = [16, 18, 11, 38, 39, 40]  # Taking random ids of product.template
produtc_templates = self.env['product.template']
for p_id in p_ids:
    binary_data = produtc_templates.search([('id', '=', p_id)]).image
    mimetype = guess_mimetype(base64.b64decode(binary_data))
    file_path = ""
    if mimetype == 'image/png':
        file_path = "/home/Downloads/" + str(p_id) + ".png"
    elif mimetype == 'image/jpeg':
        file_path = "/home/Downloads/" + str(p_id) + ".jpeg"

    if file_path:
        with open(file_path, "wb") as imgFile:
            imgFile.write(base64.b64decode(binary_data))

关于python - 将 odoo 图像存储到文件系统中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49747190/

相关文章:

python - 捕捉并忽略信号

python - 修改 Pandas 中的时间戳以使索引唯一

python - 如何在odoo中显示没有公司的联系人?

inheritance - 如何继承odoo v8上的_constraints?

report - 如何在 Qweb 中自定义 Odoo 11 中的报告?如何将其他模型的数据发送到qweb报告?

python - 转换为列表时保留 datetime64 的原始格式

python - 字符串连接类型错误: can only concatenate str (not "int") to str"

odoo - 如何在网站中获取odoo二进制字段下载链接

odoo - 有没有办法在 Qweb 中使用小数精度显示变量?

javascript - 如何在POS收据中添加新字段/如何继承js文件