如何解决这个错误?

时间:2018-06-18 08:44:10

标签: python xml odoo

为什么我收到此错误?

Traceback(most recent call last):
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
650, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
310, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File
"/home/prachh/odoo-new/11/odoo/odoo/tools/pycompat.py", line
87, in reraise
raise value
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
692, in dispatch
result = self._call_function(**self.params)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
342, in _call_function
return checked_call(self.db, *args, **kwargs)
File
"/home/prachh/odoo-new/11/odoo/odoo/service/model.py", line
97, in wrapper
return f(dbname, *args, **kwargs)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
335, in checked_call
result = self.endpoint(*a, **kw)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
936, in call
return self.method(*args, **kw)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
515, in response_wrap
response = f(*args, **kw)
File
"/home/prachh/odoo-new/11/odoo/addons/web/controllers/main.py", line
934, in call_button
action = self._call_kw(model, method, args, {})
File
"/home/prachh/odoo-new/11/odoo/addons/web/controllers/main.py", line
922, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File
"/home/prachh/odoo-new/11/odoo/odoo/api.py", line
689, in call_kw
return call_kw_multi(method, model, args, kwargs)
File
"/home/prachh/odoo-new/11/odoo/odoo/api.py", line
680, in call_kw_multi
result = method(recs, *args, **kwargs)
File
"/home/prachh/odoo-new/11/enterprise/account_bank_statement_import_csv/wizard/account_bank_statement_import_csv.py", line
19, in import_file
return super(AccountBankStatementImport, self).import_file()
File
"/home/prachh/odoo-new/11/apps/account_bank_statement_import_bankgiro/models/inherited_account_bank_statement_import.py", line
18, in import_file
else:
File
"/home/prachh/odoo-new/11/apps/account_bank_statement_import_bankgiro/models/inherited_account_bank_statement_import.py", line
26, in _parse_file_txt
File
"/home/prachh/odoo-new/11/apps/account_bank_statement_import_bankgiro/models/inherited_account_bank_statement_import.py", line
107, in records
'antal_extra_referansposter': line[18:26], 'antal_insattningsposter': line[26:34]}, KeyError: b'01' 
我放了他的.decode(" utf-8")是不是?如果这是错的,请检查此代码,以便我需要把它放在哪里?

# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
import base64


class AccountBankStatementImportBankgiro(models.TransientModel):
    _inherit = 'account.bank.statement.import'

    @staticmethod
    def _check_bg(data_file):
        return data_file.strip().startswith(b'01BGMAX')

    @api.multi
    def import_file(self):
        if not self._check_bg(base64.standard_b64decode(self.data_file)):
            return super(AccountBankStatementImportBankgiro, self).import_file()
        else:
            return self._parse_file_txt(base64.standard_b64decode(self.data_file))

    def _parse_file_txt(self, data_file):
        st_ids = []
        journal_id = self._context.get('journal_id')

        for line in data_file.splitlines():

            vals = self.records(line)

            if vals['post'] == 'startpost':
                date = vals['skrivdag_tidsstampel'][:8]
                id = self.env['account.bank.statement'].create({
                    'name': ("%s-%s") % (vals['layoutnamn'], vals['skrivdag_tidsstampel']),
                    'journal_id': journal_id,
                    'date': date,
                })
                st_ids.append(id.id)

            if vals['post'] == 'oppningspost':
                bgnummer = ("%s-%s") % (vals['mottagarbankgironummer'][2:6], vals['mottagarbankgironummer'][6:])

            if vals['post'] == 'organisationsnummerpost':
                result = self.env['res.partner'].search([('ref', '=', vals['organisationsnummer'][2:])], limit=1)

                if result and lid:
                    st_line = self.env['account.bank.statement.line'].search([('id', '=', lid.id)])
                    st_line.write({
                        'partner_id': result[0]['id']
                    })

            if vals['post'] == 'betalningspost':
                referens = vals['referens'] if vals['referens'] != "" else "."
                amount = float(vals['betalningsbelopp']) / 100

                lid = self.env['account.bank.statement.line'].create({
                    'statement_id': id.id,
                    'name': referens.decode('iso-8859-1'),
                    'journal_id': journal_id,
                    'amount': amount,
                    'date': date,
                })

            if vals['post'] == 'insattningspost':
                referens = ("Bg %s %s") % (bgnummer, vals['insattningslopnummer'])
                amount = -float(vals['insattningsbelopp']) / 100

                lid = self.env['account.bank.statement.line'].create({
                    'statement_id': id.id,
                    'name': referens,
                    'journal_id': journal_id,
                    'amount': amount,
                    'date': date
                })

        if st_ids:
            action = self.env.ref('account.action_bank_reconcile_bank_statements')

            return {
                'name': action.name,
                'tag': action.tag,
                'context': {
                    'statement_ids': st_ids,
                },
                'type': 'ir.actions.client',
            }

    @staticmethod
    def records(line):
        return {
            '01': {'post': 'startpost', 'layoutnamn': line[2:22].strip(), 'skrivdag_tidsstampel': line[24:44],
                   'testmarkering': line[44]},
            '05': {'post': 'oppningspost', 'mottagarbankgironummer': line[2:12], 'valuta': line[22:25]},
            '20': {'post': 'betalningspost', 'avsandarbankgironummer': line[2:12], 'referens': line[12:37].strip(),
                   'betalningsbelopp': line[37:55], 'referenskod': line[55]},
            '21': {'post': 'avdragspost', 'avsandarbankgironummer': line[2:12], 'referens': line[12:37],
                   'betalningsbelopp': line[37:55], 'referenskod': line[55]},
            '22': {'post': 'extra referensnummerpost'},
            '23': {'post': 'extra referensnummerpost negativ'},
            '25': {'post': 'informationspost', 'informationstext': line[2:52]},
            '26': {'post': 'namnpost', 'betalarens_namn': line[2:37].strip()},
            '27': {'post': 'adresspost1', 'betalarens_adress': line[2:37].strip(),
                   'betalarens_postnummer': line[37:46].strip()},
            '28': {'post': 'adresspost2', 'betalarens_ortsadress': line[2:37].strip()},
            '29': {'post': 'organisationsnummerpost', 'organisationsnummer': line[2:14]},
            '15': {'post': 'insattningspost', 'mottagarbankgironummer': line[2:37], 'betalningsdag': line[37:45],
                   'insattningslopnummer': line[45:50], 'insattningsbelopp': line[50:68], 'antal_betalningar': line[71:79]},
            '70': {'post': 'slutpost', 'antal_betalposter': line[2:10], 'antal_avdragsposter': line[10:18],
                   'antal_extra_referansposter': line[18:26], 'antal_insattningsposter': line[26:34]},
        }[line[:2].decode('utf-8')]


2 个答案:

答案 0 :(得分:0)

听起来像data_file是bytes object,而不是str。在这种情况下,.startsiwith需要一个字节参数(写为b'text'),而不是一个unicode字符串(写为'text')。在这种情况下,你想要

 return data_file.strip().startswith(b'01BGMAX')

证明

b'hello world '.strip().startswith('hello')

# ---------------------------------------------------------------------------
# TypeError                                 Traceback (most recent call last)
# <ipython-input-38-cc253315406b> in <module>()
# ----> 1 b'hello world '.strip().startswith('hello')
# 
# TypeError: startswith first arg must be bytes or a tuple of bytes, not str


b'hello world '.strip().startswith(b'hello')
# True

答案 1 :(得分:-1)

字节文字以'b'开头。它创建一个字节类型的实例而不是字符串类型。 您直接传递字符串时收到错误。 尝试

return data_file.strip()。startswith(b'01BGMAX')

这将告诉python它是一个字节序列而不是Unicode字符