网页服务

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

  • XML-RPC

  • JSON-RPC

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

Odoo 可通过 XML-RPC/JSON-RPC 接口进行访问,许多语言都存在相应的库。

XML-RPC 库

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

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

向客户端添加一个新服务

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

另请参见

  • 外部接口: 关于 XML-RPC 的深入教程,包含多种编程语言的示例。

JSON-RPC 库

以下是一个使用标准 Python 库 urllib.requestjson 与 Odoo 服务器交互的 Python 3 程序示例。此示例假设已安装 生产力 应用(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 的示例可以轻松进行调整。