### JSON-RPC 库
下面的例子是一个Python程序与标准的Python库Odoo服务器交互 `urllib2` 和 `json`:
~~~ python
import json
import random
import urllib2
def json_rpc(url, method, params):
data = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": random.randint(0, 1000000000),
}
req = urllib2.Request(url=url, data=json.dumps(data), headers={
"Content-Type":"application/json",
})
reply = json.load(urllib2.urlopen(req))
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)
~~~
这里是同一个程序,使用了库[jsonrpclib](https://pypi.python.org/pypi/jsonrpclib):
~~~ python
import jsonrpclib
# server proxy object
url = "http://%s:%s/jsonrpc" % (HOST, PORT)
server = jsonrpclib.Server(url)
# log in the given database
uid = server.call(service="common", method="login", args=[DB, USER, PASS])
# helper function for invoking model methods
def invoke(model, method, *args):
args = [DB, uid, PASS, model, method] + list(args)
return server.call(service="object", method="execute", args=args)
# create a new note
args = {
'color' : 8,
'memo' : 'This is another note',
'create_uid': uid,
}
note_id = invoke('note.note', 'create', args)
~~~
例子可以很容易地适应 XML-RPC 到 JSON-RPC.
Note
有一些高级的API在不同的语言来访问Odoo系统没有明确*经历* XML-RPC 到 JSON-RPC, 如同这样:
* [https://github.com/akretion/ooor](https://github.com/akretion/ooor)
* [https://github.com/syleam/openobject-library](https://github.com/syleam/openobject-library)
* [https://github.com/nicolas-van/openerp-client-lib](https://github.com/nicolas-van/openerp-client-lib)
* [https://pypi.python.org/pypi/oersted/](https://pypi.python.org/pypi/oersted/)
* [https://github.com/abhishek-jaiswal/php-openerp-lib](https://github.com/abhishek-jaiswal/php-openerp-lib)
[[1]](https://www.odoo.com/documentation/9.0/howtos/backend.html#id2) 这是可能的 [`禁用某些字段的自动创建`](https://www.odoo.com/documentation/9.0/reference/orm.html#openerp.models.Model._log_access "openerp.models.Model._log_access")
[[2]](https://www.odoo.com/documentation/9.0/howtos/backend.html#id1) 写作原始SQL查询是可能的,但需要照顾它绕过Odoo认证和安全机制。