【问题标题】:Odoo 12 python write xls File fails (PermissionError: [Errno 13] Permission denied:)Odoo 12 python 写入 xls 文件失败(PermissionError: [Errno 13] Permission denied :)
【发布时间】:2019-11-21 09:45:29
【问题描述】:

我从 odoo 生成 xls 文件,代码在我的笔记本电脑上工作,但在服务器机器上却不行 我尝试了这两个命令:

1- sudo chmod -R 777 /usr/local/lib/python3.6/

2-sudo chown -R 777 /odoo/

但什么都没有改变

感谢您的帮助

模块 dangerous.product.wizard 的文件代码

# -*- coding:utf-8 -*-
# here is the file of generation xls file 
from datetime import timedelta
import xlwt
from odoo import models, fields, api, _


class LiberationPfWizard(models.TransientModel):
    _name = 'dangerous.product.wizard'

    date_from = fields.Date(string='From', required=True, default=fields.Date.today().replace(month=1, day=1))
    date_to = fields.Date(string='To', required=True, default=fields.Date.today().replace(month=12, day=31))
    product_ids = fields.Many2many('product.product',
                                   string="Products list",
                                   default=lambda self: self.env['product.product'].search([('is_dangerous', '=', True)]))

    @api.multi
    def print_report_xls(self):
        workbook = self.sudo().create_workbook()
        return self.env['report.xls'].report_action(workbook, _('Dangerous product Excel'))

    def get_report_lines(self):
        lines = []
        product_ids = self.env['product.product'].with_context(dict(self.env.context, to_date=self.date_from)).search([
            ('id', 'in', self.product_ids.ids)
        ])
        for product_id in product_ids:
            data = {
                'product_name': product_id.name,
                'product_technical_description': product_id.technical_description,
                'onu_number': product_id.onu_number,
            }
            moves = self.env['stock.move'].search([
                ('state', '=', 'done'),
                ('product_id', '=', product_id.id),
                ('date', '>=', self.date_from),
                ('date', '<', self.date_to + timedelta(days=1)),
            ])
            in_qty = sum(moves.filtered(
                lambda move: move.location_id.usage in ['customer', 'supplier', 'inventory'] and move.location_dest_id.usage == 'internal'
            ).mapped('quantity_done'))
            out_qty = sum(moves.filtered(
                lambda move: move.location_id.usage == 'internal' and move.location_dest_id.usage in ['production', 'customer', 'supplier', 'inventory']
            ).mapped('quantity_done'))
            data['initial_stock'] = product_id.qty_available
            data['in_qty'] = in_qty
            data['out_qty'] = out_qty
            lines.append(data)
        return lines

    def create_workbook(self):
        lines = self.get_report_lines()

        date_from = self.date_from
        date_to = self.date_to
        workbook = xlwt.Workbook()
        xlwt.add_palette_colour("teal", 0x21)
        workbook.set_colour_RGB(0x21, 0, 128, 128)
        xlwt.add_palette_colour("magenta", 0x22)
        workbook.set_colour_RGB(0x22, 224, 17, 95)
        xlwt.add_palette_colour("light_grey", 0x23)
        workbook.set_colour_RGB(0x23, 222, 222, 222)

        colorized = xlwt.easyxf(
            'font:height 220,bold True;pattern: pattern solid, fore_colour light_grey;align: horiz center, vert center; '
            'border: left thin,right thin,top thin,bottom thin')
        value = xlwt.easyxf(
            'font:height 220;align: horiz center, vert center;border: left thin,right thin,top thin,bottom thin')
        teal = xlwt.easyxf(
            'font:height 220,colour white,bold True;pattern: pattern solid, '
            'fore_colour teal;align: horiz center, vert center; '
            'border: left thin,right thin,top thin,bottom thin')
        magenta = xlwt.easyxf(
            'font:height 220,colour white,bold True;pattern: pattern solid, '
            'fore_colour magenta;align: horiz center, vert center; '
            'border: left thin,right thin,top thin,bottom thin')
        sheet = workbook.add_sheet(_('Liberation PF'))

        sheet.write_merge(1, 1, 0, 6, _('Monthly Declaration of Dangerous Raw Materials'), magenta)
        sheet.write_merge(2, 2, 0, 6, _('FROM %s TO %s') % (str(date_from), str(date_to)), teal)
        sheet.write(3, 0, _('NAME'), colorized)
        sheet.write(3, 1, _('TECHNICAL DESCRIPTION'), colorized)
        sheet.write(3, 2, _('N° ONU-CAS-CEE-EINCS'), colorized)
        sheet.write(3, 3, _('STOCK AT %s') % str(self.date_from - timedelta(days=1)), colorized)
        sheet.write(3, 4, _('ENTERED'), colorized)
        sheet.write(3, 5, _('QUANTITY USED'), colorized)
        sheet.write(3, 6, _('BALANCE AT %s') % str(self.date_to), colorized)
        l = 4
        for line in lines:
            sheet.write(l, 0, line.get('product_name'), value)
            sheet.write(l, 1, line.get('product_technical_description') or '/', value)
            sheet.write(l, 2, line.get('onu_number') or '/', value)
            sheet.write(l, 3, line.get('initial_stock'), value)
            sheet.write(l, 4, line.get('in_qty'), value)
            sheet.write(l, 5, line.get('out_qty'), value)
            sheet.write(l, 6, abs(line.get('initial_stock') + line.get('in_qty') - line.get('out_qty')), value)
            l += 1

        sheet.col(0).width = 256 * 48
        sheet.col(1).width = 256 * 72
        sheet.col(2).width = 256 * 48
        for i in range(3, 7):
            sheet.col(i).width = 256 * 28
        return workbook

模块report.xls的文件代码仅在第21行,report_action中的服务器机器中出错workbook.save(filename)

# -*- coding: utf-8 -*-

import base64

from odoo import models, fields, api, _
from odoo.exceptions import UserError


class ReportXLS(models.TransientModel):
    _name = "report.xls"
    _description = "Report xls"

    file_name = fields.Binary('Excel Report', readonly=True, attachment=True)
    data = fields.Binary('File', readonly=True)
    name = fields.Char('Filename', readonly=True)

    @api.model
    def report_action(self, workbook, filename=_("XLS REPORT")):
        if workbook:
            filename = '%s.%s' % (filename, 'xls')
            workbook.save(filename)
            file = open(filename, "rb")
            file_data = file.read()
            out = base64.encodebytes(file_data)
            record = self.env['report.xls'].create({
                'file_name': out,
                'data': out,
                'name': filename
            })
            return {
                'type': 'ir.actions.act_window',
                'res_model': 'report.xls',
                'view_mode': 'form',
                'view_type': 'form',
                'res_id': record.id,
                'target': 'new',
            }
        raise UserError(
            _('There is no XLS File to print !')
        )

这里是完整的错误消息

错误:Odoo 服务器错误

Traceback(最近一次调用最后一次):文件 “/odoo/odoo-server/odoo/http.py”,第 656 行,在 _handle_exception 中 return super(JsonRequest, self)._handle_exception(exception) 文件“/odoo/odoo-server/odoo/http.py”,第 314 行,在 _handle_exception raise pycompat.reraise(type(exception), exception, sys.exc_info()[2]) 文件 "/odoo/odoo-server/odoo/tools/pycompat.py", 第 87 行,在加注中 提高值文件“/odoo/odoo-server/odoo/http.py”,第 698 行,在调度中 结果 = self._call_function(**self.params) 文件“/odoo/odoo-server/odoo/http.py”,第 346 行,在 _call_function return checked_call(self.db, *args, **kwargs) File "/odoo/odoo-server/odoo/service/model.py", line 97, in wrapper return f(dbname, *args, **kwargs) File "/odoo/odoo-server/odoo/http.py", line 339, in checked_call 结果 = self.endpoint(*a, **kw) 文件“/odoo/odoo-server/odoo/http.py”,第 941 行,在 call 中 return self.method(*args, **kw) 文件“/odoo/odoo-server/odoo/http.py”,第 519 行,在 response_wrap 响应 = f(*args, **kw) 文件“/odoo/odoo-server/addons/web/controllers/main.py”,第 966 行,在 呼叫按钮 action = self._call_kw(model, method, args, {}) 文件“/odoo/odoo-server/addons/web/controllers/main.py”,第 954 行,在 _call_kw return call_kw(request.env[model], method, args, kwargs) File "/odoo/odoo-server/odoo/api.py", line 749, in call_kw return _call_kw_multi(method, model, args, kwargs) 文件“/odoo/odoo-server/odoo/api.py”,第 736 行,在 _call_kw_multi 结果=方法(recs,*args,**kwargs)文件“/odoo/custom/lsee/quality_pharm_report/wizard/dangerous_product_balance_wizard.py”, 第 20 行,在 print_report_xls 中 return self.env['report.xls'].report_action(workbook, _('Dangerous product Excel')) 文件 “/odoo/custom/lsee/report_xls/wizard/report_xls.py”,第 21 行,在 报告动作 workbook.save(文件名)文件“/usr/local/lib/python3.6/dist-packages/xlwt/Workbook.py”,第 710 行, 在保存 doc.save(filename_or_stream, self.get_biff_data()) 文件“/usr/local/lib/python3.6/dist-packages/xlwt/CompoundDoc.py”,行 262,在保存中 f = open(file_name_or_filelike_obj, 'w+b') PermissionError: [Errno 13] Permission denied: 'Produits dangereux Excel.xls'

【问题讨论】:

  • 抛出错误的是您尝试写入的文件的位置,而不是可执行文件。
  • 您有什么建议吗谢谢
  • 你没有提供代码,所以我们只能猜测问题出在哪里。
  • 另外,错误指出了它无法访问的确切文件:Produits dangereux Excel.xls
  • 我添加了代码感谢帮助

标签: python python-3.x odoo odoo-12


【解决方案1】:

我会坚持使用 Odoo 本身用于其报告或导出文件的解决方案:使用 /tmp 作为临时(双关语)文件目录。在“正常”或“常规”服务器配置中,几乎所有应用程序都可以使用此目录,而无需考虑文件访问。

因此,您必须更改自定义模块用于创建 Excel 文件的路径。 (无法进一步提供帮助,因为您没有分享您的代码)

【讨论】:

  • filename 只是执行上下文中的相对路径。只需添加 tmp 目录并使其成为绝对文件路径 -> '/tmp/' + filename.
猜你喜欢
  • 2017-02-12
  • 2019-11-27
  • 1970-01-01
  • 2019-07-31
  • 2016-08-17
  • 2017-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多