文章目录
- Odoo - JsonRPC
 - 1. Odoo内方法结构(接收端)
 - 2. POST接口请求结构(发送端)
 - 3. 实例测试
 
Odoo - JsonRPC
1. Odoo内方法结构(接收端)
# -*- coding: utf-8 -*-
import odoo
import logging
import traceback
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import MissingError, UserError, ValidationError, AccessError
class YourModelName(models.Model):
    _name = 'your.model.name'
    @api.model
    def test_jsonrpc(self, args):
        try:
            # TODO SOMETHINGS
            return_json = {
                'code': "SUCCESS",
                'state': 'success',
                'error_msg': '',
                'datas': [
                    {
                        "code": "A01",
                        "name": "名称01",
                        # ...
                    },
                    {
                        "code": "A02",
                        "name": "名称02",
                        # ...
                    }
                    # ...
                ]
            }
        except Exception as e:
            return_json = {
                'code': "ERROR_001",
                'state': 'error',
                'error_msg': 'Error: %s.' % str(traceback.format_exc()),
                'datas': []
            }
        return return_json
 
2. POST接口请求结构(发送端)
# -*- coding:utf-8 -*-
import json
import uuid
import pprint
import urllib.request
HOST = "xxx.xxx.xxx.xxx"
PORT = 8069
URL = "http://%s:%s/jsonrpc" % (HOST, PORT)
DB_NAME = "odoo12"
USERID = 2
USERNAME = "admin"
PASSWORD = "admin"
ModelName = "your.model.name"
FunctionName = "test_jsonrpc"
UUID = str(uuid.uuid4())
data = {
    "id": UUID,       # 随机码
    "jsonrpc": "2.0",       # 固定值
    "method": "call",       # 固定值
    "params": {
        "service": "object",# 固定值
        "method": "execute",# 固定值
        "args": [
            DB_NAME,        # 数据库名称
            USERID,         # 接口用户ID
            PASSWORD,       # 接口用户密码
            ModelName,      # 模型
            FunctionName,   # 方法
            []              # 参数结构体
        ]
    }
}
req = urllib.request.Request(url=URL, data=json.dumps(data).encode(), headers={"Content-type": "application/json"})
reply = json.loads(urllib.request.urlopen(req).read().decode('UTF-8'))
pprint.pprint(reply)
########################返回结果结构#######################
------------------------成功结果---------------------------
{
    'id': 'ef0d3de6-30b4-4104-9272-47d51d358b70',
    'jsonrpc': '2.0',
    'result': {
        'code': 'SUCCESS',
        'state': 'success',
        'error_msg': 'success',
        'datas': [
            {
                'code': '10001',
                'name': '名称01',
                'lines': [
					{
						'a':1,
						'b':2
					},
					{
						'a':3,
						'b':4
					}
					# ...
				]
            },
            {
                'code': '10002',
                'name': '名称02',
                'lines': []
            }
            # ...
        ],
    }
}
---------------------------------------------------------
------------------------失败结果---------------------------
{
    'id': '055f70e0-1d2a-4cf5-983a-68db9e40ee80',
    'jsonrpc': '2.0',
    'result': {
        'state': 'error',
        'code': 'ERROR_0001',
        'error_msg': '错误: 详细错误信息.',
        'datas': []
    }
}
---------------------------------------------------------
#########################################################
 
3. 实例测试
- Odoo内维护一个jsonrpc的方法:test_jsonrpc
# -*- coding: utf-8 -*- import odoo import logging import traceback from odoo import api, fields, models, tools, SUPERUSER_ID, _ from odoo.exceptions import MissingError, UserError, ValidationError, AccessError class IrActions(models.Model): _name = 'ir.actions.actions' _description = 'Actions' _table = 'ir_actions' _order = 'name' @api.model def test_jsonrpc(self, args): try: # TODO SOMETHINGS return_json = { 'code': "SUCCESS", 'state': 'success', 'error_msg': '', 'datas': [ { "code": "A01", "name": "名称01", # ... }, { "code": "A02", "name": "名称02", # ... } # ... ] } except Exception as e: return_json = { 'code': "ERROR", 'state': 'error', 'error_msg': 'Error: %s.' % str(traceback.format_exc()), 'datas': [] } return return_json 
- 在其他系统中进行调用测试
# -*- coding:utf-8 -*- import json import uuid import pprint import urllib.request HOST = "localhost" PORT = 8069 URL = "http://%s:%s/jsonrpc" % (HOST, PORT) DB_NAME = "odoo12_db" USERID = 2 USERNAME = "admin" PASSWORD = "admin" ModelName = "ir.actions.actions" FunctionName = "test_jsonrpc" UUID = str(uuid.uuid4()) data = { "id": UUID, # 随机码 "jsonrpc": "2.0", # 固定值 "method": "call", # 固定值 "params": { "service": "object",# 固定值 "method": "execute",# 固定值 "args": [ DB_NAME, # 数据库名称 USERID, # 接口用户ID PASSWORD, # 接口用户密码 ModelName, # 模型 FunctionName, # 方法 [] # 参数结构体 ] } } req = urllib.request.Request(url=URL, data=json.dumps(data).encode(), headers={"Content-type": "application/json"}) reply = json.loads(urllib.request.urlopen(req).read().decode('UTF-8')) pprint.pprint(reply) 
- 结果示例
3.1 若程序正常执行无错误,则返回信息结构如下:

3.2 如果try语句中执行异常,返回错误信息结构如下:
3.3 如果身份验证或者请求参数有误,返回错误信息结构如下:

3.4 注意如果host和port不对的话,抛出的是Request的请求异常:

 
🎉如果对你有所帮助,可以点赞、关注、收藏起来,不然下次就找不到了🎉
【点赞】⭐️⭐️⭐️⭐️⭐️
 【关注】⭐️⭐️⭐️⭐️⭐️
 【收藏】⭐️⭐️⭐️⭐️⭐️
Thanks for watching.
 –Kenny

















![[Android Studio] Android Studio生成数字证书,为应用签名](https://img-blog.csdnimg.cn/24b696d76d374a9992017e1625389592.gif)
