我如何在线程中获得odoo环境

时间:2019-02-13 05:30:27

标签: python-3.x odoo environment

在我编写此代码的模型中,我正在尝试为此功能向特定用户发送消息

class SkypeBot(models.Model):
    _name = 'my.skype'
    _inherit = ['mail.thread', 'mail.activity', 'res.users']
    _description = 'My Skype'


    skype_login = fields.Char('Your skype Login')
    skype_password = fields.Char('Your skype password')
    skype_message = fields.Char(store=True)

    @api.multi
    def msg(self, message):

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

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

        self.env['mail.message'].create({'message_type': 'notification',
                                         'subtype': self.env.ref('mail.mt_comment').id,  # subject type
                                         'body': message,
                                         'subject': 'Message subject',
                                         'partner_ids': [(4, partner_id), ],
                                         # partner to whom you send notification
                                         })

我需要将odoo环境连接到在此处调用的线程,以便可以从SkypeBot类中轻松调用msg方法并将消息发送给用户。正确的做法

class MySkype(skpy.SkypeEventLoop):
    def onEvent(self, event):
        if isinstance(event, skpy.SkypeNewMessageEvent):  

            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(event)
            _logger.info('--------' * 5)
            _logger.warning(message)
            _logger.info('--------' * 5)

            sbot = skype_model.SkypeBot()
            sbot.msg(message)

from skpy import Skype

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

1 个答案:

答案 0 :(得分:1)

您可以尝试此代码

import odoo
DB_NAME = 'YOURDBNAME'
ODOO_CONF = '/opt/odoo/configurations/odoo.conf YOUR CONF PATH'
UID = odoo.SUPERUSER_ID
odoo.tools.config.parse_config(['--config=%s' % ODOO_CONF])
with odoo.api.Environment.manage():
     registry = odoo.modules.registry.RegistryManager.get(DB_NAME)
     with registry.cursor() as cr:
          # Load our context and environment given the database cursor and UID
          ctx = odoo.api.Environment(cr, UID, {})['res.users'].context_get()
          env = odoo.api.Environment(cr, UID, ctx)
          # INSERT YOUR ENV 
          message = env['my.skype'].msg()
          try:
              cr.commit()
          except Exception:
              cr.rollback()
              raise

,但是您必须正确安装odoo(dist-package中的odoo),否则python不会检测到此导入odoo(找不到名为odoo的错误模块),如果python未检测到导入odoo,只需将代码放在odoo文件夹中使这项工作