1

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

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

正如您从日志中看到的那样,生成了消息,但随后代码停止并发生错误可能是什么问题以及如何处理它

4

1 回答 1

2

需要使用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)
于 2019-02-22T13:51:39.390 回答