Web 服务¶
web-service 模块为所有 Web 服务提供了一个通用接口:
XML-RPC
JSON-RPC
也可以通过分布式对象机制访问业务对象。它们都可以通过带有上下文视图的客户端界面进行修改。
可以通过 XML-RPC/JSON-RPC 接口访问 Odoo,许多语言都提供了相应的库。
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
向客户端添加新服务
编写一个 Python 程序,能够向运行 Odoo 的计算机(您自己的或讲师的)发送 XML-RPC 请求。该程序应显示所有会话及其对应的座位数,还应为一门课程创建一个新会话。
更多内容
外部 API:关于 XML-RPC 的深入教程,其中的示例涵盖多种编程语言。
JSON-RPC 库¶
以下示例是一个 Python 3 程序,它使用标准 Python 库 urllib.request 和 json 与 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。
Note
各种语言中有许多高层 API 可用于访问 Odoo 系统,而无需 显式 通过 XML-RPC 或 JSON-RPC,例如:
https://github.com/akretion/ooor(OOOR:Python 高级 API 库)
https://github.com/OCA/odoorpc(OdoORPC:Python 高级 API 库)
https://github.com/nicolas-van/openerp-client-lib(JavaScript 高级 API 库)
https://github.com/abhishek-jaiswal/php-openerp-lib(PHP 高级 API 库)