将Odoo服务器操作添加到自定义模块

时间:2015-11-04 13:41:22

标签: python openerp odoo-8

我有一个我为Odoo V8编写的自定义模块,它为不同的表单添加了各种字段等,并添加了一些控制器等。

我现在需要添加服务器操作,但文档在这方面似乎很差。

我在继承的类下的models.py中有一个函数。

class res_partner(osv.osv):
#update Jira customer list (called on update/save of res.partner)
def updatejira(self):
    r = requests.post('http://10.10.15.39:4000',data='Worked!')

我希望能够调用此函数向Jira发出请求,以便在创建或更新客户时更新其客户列表。

我已将此添加到我的templates.xml

<record model="ir.actions.server" id="update_jira">
    <field name="name">Res Partner Server Action</field>
    <field name="model_id" ref="model_res_partner"/>
    <field name="condition">True</field>
    <field name="code">
        self.updatejira()
    </field>
</record>

我是否以正确的方式解决这个问题?我不想在模块中而不是在UI中执行此操作。但是,文档再次稀疏,并没有真正包含在示例中。

由于

@miw

像这样?

import requests
from openerp import models, api


class res_partner(models.Model):
    #_name = "ResPartnerChange"
    _inherit = "res.partner"

    def update_jira(self):
        r = requests.post('http://10.10.15.39:4000',data='Worked!')
        f = open("test.log","a")
        f.write(r.text)
        return r.text

    def write(self, vals):
        res = super(extendedProject, self).write(vals)
        for p in self:
            self.update_jira()
        return res

res_partner()

这似乎不起作用。

编辑--------

到目前为止,感谢您的帮助。这是我最近的尝试。如果我用@ api.onchange装饰它,我可以让服务器调用update_jira函数,尽管它一直被调用。所以我试图覆盖write函数来调用update_jira。但它似乎没有被召唤。我做错了什么?

__author__ = 'karl'
import requests
import json
from openerp import models, api

class ResPartnerChange(models.Model):

    _inherit = "res.partner"

    def update_jira(self):
        if self.jira_id == 0: #If the ID is 0 then the customer does not exist so create it
            H = {'Content-Type':'application/json'}
            customer = {
              "optionvalue": str(self.name),
              "id": 0,
              "sequence": 0,
              "disabled": 'false',
              "childOptions": [
                {}
              ]
            }
            req = requests.post('https://jira.example.com/rest/jiracustomfieldeditorplugin/1.1/user/customfieldoption/customfield_10128', auth=('user','pass'), headers=H, data=json.dumps(customer))

            #store the json responce from Jira
            jdata = json.loads(req.text)

            #Change the Jira ID value to the received one
            # res = {
            # 'value': {
            #
            #     'jira_id': jdata['id']
            #         }
            # }
            vals = []
            vals['jira_id'] = jdata['id']

        else:
            #update jira customer
            data = self.name, self.jira_id, self.active
            pass
        return vals

    def write(self):
        vals = self.update_jira()
        res = super(ResPartnerChange, self).write(vals)
        return res

ResPartnerChange()

2 个答案:

答案 0 :(得分:2)

所以我想通了。我没有覆盖write方法。相反,我使用@ api.constrains方法装饰器,只有在调用create或write方法时才会激活它。

如果有人有兴趣,这是我的代码。在保存Odoo客户时,我的方法被调用,然后验证它是客户而不是供应商,用户等(他们都使用res.partner)。然后它进行快速逻辑测试,以查看客户是新的(jira id 0)还是现有的(0以外的东西)。根据它的不同,它会调用相关的Jira API来创建或更新存储客户详细信息的自定义字段。

感谢@miw指出我正确的方向。

 __author__ = 'karl'
import requests
import json
from openerp import models, api
import logging
_logger = logging.getLogger(__name__)

    class ResPartnerChange(models.Model):

        _inherit = "res.partner"
        @api.constrains('name','active')
        def update_jira(self):
            #Only apply to customers not suppliers users etc as they all use the res.partner model
            if self.customer == True:

                if self.jira_id == 0: #If the ID is 0 then the jira customer does not exist so create it
                    _logger.info('Not a Customer yet - Creating Jira Customer')
                    H = {'Content-Type':'application/json'}
                    customer = {
                      "optionvalue": str(self.name),
                      "id": 0,
                      "sequence": 0,
                      "disabled": 'false',
                      "childOptions": [
                        {}
                      ]
                    }
                    req = requests.post('https://example.com/rest/jiracustomfieldeditorplugin/1.1/user/customfieldoption/customfield_10128', auth=('apiuser','apipass'), headers=H, data=json.dumps(customer))
                    _logger.info(req.text)
                    #store the json responce from Jira
                    jdata = json.loads(req.text)

                    #create values dictionary
                    vals = {}
                    vals['jira_id'] = jdata['id']
                    self.write(vals)

                else:
                    #update jira customer
                    _logger.info('Existing Customer - Updating Jira Customer')
                    vals = {}
                    vals['name'] = self.name
                    vals['active'] = self.active
                    if self.active:
                        disabled = "false"
                    else:
                        disabled = "true"
                    H = {'Content-Type':'application/json'}
                    customer = {
                      "optionvalue": str(self.name),
                      "id": str(self.jira_id),
                      "sequence": 0,
                      "disabled": disabled,
                      "childOptions": [
                        {}
                      ]
                    }
                    req = requests.put('https://example.com/rest/jiracustomfieldeditorplugin/1.1/user/customfieldoption/customfield_10128/'+str(self.jira_id), auth=('apiuser','apipass'), headers=H, data=json.dumps(customer))
                    _logger.info(req.text)

                return True


            else:
                return True


    ResPartnerChange()

答案 1 :(得分:1)

我不确定你是否正朝着正确的方向前进。任何python代码(嗯,大多数......)都在Odoo服务器中执行,而不是在Browser / UI中执行。因此,创建一个类型为&#34; object&#34;的按钮可能更有意义。使用名称=&#34; method_name&#34;,然后您将使用它来调用Jira。

另一种选择是覆盖子类中的write()方法以添加您的调用,如下所示:

    def write(self, vals):
        res = super(extendedProject, self).write(vals)
        for p in self:
            # do the call to JIRA here for each partner p, using p.field1, p.field2 etc. 
        return res

vals是一个包含要存储的修改值的字典; self是一个记录集,包含存储值的所有记录。请注意,从您致电write返回后,Odoo中的交易仍可能会回滚。

最后,您可以尝试在设置&gt;下创建服务器操作。技术&gt;行动&gt;首先是交互式服务器操作。这将允许立即反馈/测试。请注意,服务器操作在没有特定对象上下文的情况下执行,但基于计时器。

以下是该表单中的一小段文档:

# Available locals:
#  - time, datetime, dateutil: Python libraries
#  - env: Odoo Environement
#  - model: Model of the record on which the action is triggered
#  - object: Record on which the action is triggered if there is one, otherwise None
#  - workflow: Workflow engine
#  - Warning: Warning Exception to use with raise

有了这个,你需要修改你的代码,使它首先找到要推送到Jira的res.partners,然后循环它们并推送给每个伙伴的Jira。