### XML-RPC Library
下面的例子是一个Python程序与图书馆Odoo服务器交互 `xmlrpclib`:
~~~ python
import xmlrpclib
root = 'http://%s:%d/xmlrpc/' % (HOST, PORT)
uid = xmlrpclib.ServerProxy(root + 'common').login(DB, USER, PASS)
print "Logged in as %s (uid: %d)" % (USER, uid)
# Create a new note
sock = xmlrpclib.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)
~~~
练习
为客户添加新的服务
写一个能够发送XML-RPC请求PC运行Odoo Python程序(你的,还是你的教练)。这个程序应该显示所有的会话,以及相应的座位数量。它还应该为一个课程创建新的会话。
~~~ python
import functools
import xmlrpclib
HOST = 'localhost'
PORT = 8069
DB = 'openacademy'
USER = 'admin'
PASS = 'admin'
ROOT = 'http://%s:%d/xmlrpc/' % (HOST,PORT)
# 1\. 登录
uid = xmlrpclib.ServerProxy(ROOT + 'common').login(DB,USER,PASS)
print "Logged in as %s (uid:%d)" % (USER,uid)
call = functools.partial(
xmlrpclib.ServerProxy(ROOT + 'object').execute,
DB, uid, PASS)
# 2\. 读取session
sessions = call('openacademy.session','search_read', [], ['name','seats'])
for session in sessions:
print "Session %s (%s seats)" % (session['name'], session['seats'])
# 3.创建一个新 session
session_id = call('openacademy.session', 'create', {
'name' : 'My session',
'course_id' : 2,
})
~~~
而不是使用硬编码的课程标识,代码可以查找一个课程名称:
~~~ python
# 3.为“功能性”课程创建一个新的会话
course_id = call('openacademy.course', 'search', [('name','ilike','Functional')])[0]
session_id = call('openacademy.session', 'create', {
'name' : 'My session',
'course_id' : course_id,
})
~~~