如何修复odoo中的AttributeError:环境?

时间:2019-02-21 09:12:57

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

我创建了一个单独的线程,其中存在oodo环境,当我在Skype中收到新消息时,我排成一行并尝试将其作为消息在oodo中发送给用户,但出现错误

import skpy
import logging
import threading
import odoo

DB_NAME = 'odootest'
UID = odoo.SUPERUSER_ID

_logger = logging.getLogger(__name__)


registry = odoo.modules.registry.Registry.new(DB_NAME)
CR = registry.cursor()
ENV = odoo.api.Environment(CR, UID, {})


class MySkype(skpy.SkypeEventLoop):

    def onEvent(self, event):
        if isinstance(event, skpy.SkypeNewMessageEvent):
            _logger.info('--------' * 5)
            _logger.warning(event)
            _logger.info('--------' * 5)

            message = ('New message from user {} at {}: \'{} \''.format(event.msg.userId,
                                                                     event.msg.time.strftime('%H:%M dd. %d.%m.%Y'),
                                                                     event.msg.content))

            _logger.info('--------' * 5)
            _logger.warning(message)
            _logger.info('--------' * 5)

            partner_id = ENV['res.users'].search([('id', '=', 2)]).partner_id.id

            _logger.info('--------' * 5)
            _logger.warning(partner_id)
            _logger.info('--------' * 5)

            ENV['mail.message'].create({'message_type': 'notification',
                                             'subtype': ENV.ref('mail.mt_comment').id,
                                             'body': message,
                                             'subject': 'Message subject',
                                             'partner_ids': [(4, partner_id), ],
                                             })
            _logger.info('--------' * 5)
            _logger.warning('send')
            _logger.info('--------' * 5)


sk = MySkype('+3767', '12qW', autoAck=True)
thread = threading.Thread(target=sk.loop)
thread.start()

在控制台中

2019-02-21 08:45:33,569 3550 INFO ? odoo.addons.skype_bot.models.models: ---------------------------------------- 
2019-02-21 08:45:33,569 3550 WARNING ? odoo.addons.skype_bot.models.models: [SkypeNewMessageEvent]
Id: 1010
Type: NewMessage
Time: 2019-02-21 08:45:33
MsgId: 1550738733239 
2019-02-21 08:45:33,569 3550 INFO ? odoo.addons.skype_bot.models.models: ---------------------------------------- 
2019-02-21 08:45:33,570 3550 INFO ? odoo.addons.skype_bot.models.models: ---------------------------------------- 
2019-02-21 08:45:33,570 3550 WARNING ? odoo.addons.skype_bot.models.models: New message from user andreykychyc at 08:45 dd. 21.02.2019: '132123 ' 
2019-02-21 08:45:33,570 3550 INFO ? odoo.addons.skype_bot.models.models: ---------------------------------------- 
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/home/andrei/.virtualenvs/odoo-venv/lib/python3.6/site-packages/werkzeug/local.py", line 70, in __getattr__
    return self.__storage__[self.__ident_func__()][name]
KeyError: <greenlet.greenlet object at 0x7f6d76aed048>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/andrei/.virtualenvs/odoo-venv/lib/python3.6/site-packages/skpy/main.py", line 207, in loop
    self.cycle()
  File "/home/andrei/.virtualenvs/odoo-venv/lib/python3.6/site-packages/skpy/main.py", line 196, in cycle
    self.onEvent(event)
  File "/home/andrei/Projects/odoo/odoo/adoons_my/skype_bot/models/models.py", line 35, in onEvent
    partner_id = ENV['res.users'].search([('id', '=', 2)]).partner_id.id
  File "/home/andrei/Projects/odoo/odoo/odoo/models.py", line 1561, in search
    res = self._search(args, offset=offset, limit=limit, order=order, count=count)
  File "/home/andrei/Projects/odoo/odoo/odoo/addons/base/models/res_users.py", line 422, in _search
    access_rights_uid=access_rights_uid)
  File "/home/andrei/Projects/odoo/odoo/odoo/models.py", line 4055, in _search
    self.sudo(access_rights_uid or self._uid).check_access_rights('read')
  File "/home/andrei/Projects/odoo/odoo/odoo/models.py", line 4714, in sudo
    return self.with_env(self.env(user=user))
  File "/home/andrei/Projects/odoo/odoo/odoo/api.py", line 850, in __call__
    return Environment(cr, uid, context)
  File "/home/andrei/Projects/odoo/odoo/odoo/api.py", line 794, in __new__
    env, envs = None, cls.envs
  File "/home/andrei/Projects/odoo/odoo/odoo/tools/func.py", line 112, in __get__
    return self.fget.__get__(None, owner)()
  File "/home/andrei/Projects/odoo/odoo/odoo/api.py", line 767, in envs
    return cls._local.environments
  File "/home/andrei/.virtualenvs/odoo-venv/lib/python3.6/site-packages/werkzeug/local.py", line 72, in __getattr__
    raise AttributeError(name)
AttributeError: environments

从日志中可以看到,生成了消息,但是代码停止了,并且发生了错误,这可能是问题所在以及如何处理

1 个答案:

答案 0 :(得分:0)

需要使用with

    _logger.info('--------' * 5)
    _logger.warning(message)
    _logger.info('--------' * 5)

    with odoo.api.Environment.manage():
        try:

            partner_id = ENV['res.users'].search([('id', '=', 2)]).partner_id.id

            _logger.info('--------' * 5)
            _logger.warning(partner_id)
            _logger.info('--------' * 5)

            ENV['mail.message'].create({'message_type': 'notification',
                                             'subtype': ENV.ref('mail.mt_comment').id,
                                             'body': message,
                                             'subject': 'Message subject',
                                             'partner_ids': [(4, partner_id), ],
                                             })
        finally:
            ENV.cr.commit()

    _logger.info('--------' * 5)
    _logger.warning('send')
    _logger.info('--------' * 5)