Web 服务

Web 服务模块为所有 Web 服务提供了一个通用接口:

  • XML-RPC

  • JSON-RPC

业务对象还可以通过分布式对象机制访问。它们都可以通过客户端界面使用上下文视图进行修改。

Odoo 可以通过 XML-RPC/JSON-RPC 接口访问,许多语言都有相应的库支持。

XML-RPC 库

以下示例是一个 Python 3 程序,它使用 xmlrpc.client 库与 Odoo 服务器交互::

import xmlrpc.client

root = 'http://%s:%d/xmlrpc/' % (HOST, PORT)

uid = xmlrpc.client.ServerProxy(root + 'common').login(DB, USER, PASS)
print("Logged in as %s (uid: %d)" % (USER, uid))

# Create a new note
sock = xmlrpc.client.ServerProxy(root + 'object')
args = {
    'color' : 8,
    'memo' : 'This is a note',
    'create_uid': uid,
}
note_id = sock.execute(DB, uid, PASS, 'note.note', 'create', args)

Exercise

为客户端添加新服务

编写一个能够向运行 Odoo 的 PC(您的或讲师的)发送 XML-RPC 请求的 Python 程序。该程序应显示所有场次及其对应的座位数,并为其中一个课程创建新场次。

参见

  • 外部 API :深入讲解 XML-RPC 的教程,包含跨多种编程语言的示例。

JSON-RPC 库

以下示例是一个 Python 3 程序,它使用标准 Python 库 urllib.requestjson 与 Odoo 服务器交互。该示例假设已安装 生产力 应用( note )::

import json
import random
import urllib.request

HOST = 'localhost'
PORT = 8069
DB = 'openacademy'
USER = 'admin'
PASS = 'admin'

def json_rpc(url, method, params):
    data = {
        "jsonrpc": "2.0",
        "method": method,
        "params": params,
        "id": random.randint(0, 1000000000),
    }
    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'))
    if reply.get("error"):
        raise Exception(reply["error"])
    return reply["result"]

def call(url, service, method, *args):
    return json_rpc(url, "call", {"service": service, "method": method, "args": args})

# log in the given database
url = "http://%s:%s/jsonrpc" % (HOST, PORT)
uid = call(url, "common", "login", DB, USER, PASS)

# create a new note
args = {
    'color': 8,
    'memo': 'This is another note',
    'create_uid': uid,
}
note_id = call(url, "object", "execute", DB, uid, PASS, 'note.note', 'create', args)

示例可以轻松从 XML-RPC 适配到 JSON-RPC。

注解

有许多高级 API 可以在各种语言中访问 Odoo 系统,而无需 显式 使用 XML-RPC 或 JSON-RPC,例如: