This is the documentation for older versions of Odoo (formerly OpenERP).

See the new Odoo user documentation.

See the new Odoo technical documentation.

XML-RPC Web服务(XML-RPC Web Services)

XML-RPC 是一个著名的Web服务. Web 服务是一个工具,它可以再现有的网络基础设施上面设置分布式的应用程序。这些应用程序使用一种传输层的网络但是并不提供直接通过浏览器的人机界面。可扩展标记语言(XML)提供了描述远程过程调用(RPC)的词汇表,RPC是使用超文本传输协议(HTTP) 在计算机之间传输。实际上,RPC让各开发者自行定义网络调用中的接口。这些接口可以是很简单的一个函数调用也可以像大型API那样复杂.

XML-RPC 允许在两台或者更多运行不同操作系统和不同语言程序的计算机之间协同处理。比如,一个JAVA应用可以和一个Perl应用会谈,一个Perl应用可以同一个同ASP会谈的PYTHON应用会谈,等等。系统集成商往往在不同系统之间建立自己的连接,创建它们自己定义的格式的协议来进行通信,但是这造成了大量的不常使用的协议。RPC方法的程序员无需了解底层的协议、网络以及各种实施细则.

XML-RPC 可以同 Python, Java, Perl, PHP, C, C++, Ruby, Microsoft’s .NET 以及许多其他的编程语言来一起使用。它的实现被广泛用于 Unix, Linux, Windows 和 Macintosh 的平台.

一个 XML-RPC 调用实在双方之间进行的,客户端(调用程序)和服务器(被调用过程)。服务时提供在一个特定的URL上的,比如 (such as http://example.org:8080/rpcserv/).

上面我们只是接触了 XML-RPC 的表面. 我推荐 O'Reilly's "Programming Web Service with XML-RPC" 进行进一步的学习。还可以阅读以下几个环节:

接口(InterFaces)

XML-RPC

XML-RPC 架构

OpenERP 基于C/S体系结构。服务器和客户端之间的通信使用XML-RPC协议。XML-RPC是一个非常简单的协议,它允许客户端进行远程过程调用。被调用的函数,它的参数,调用结果通过XML编码并且使用HTTP进行传输。欲了解更多的关于XML-RPC的详尽信息,请参阅: http://www.xml-rpc.com.

架构(Architecture)

下面的图标综合了OpenERP的客户端和服务器结构。OpenERP的服务器和客户端通信使用 XML-RPC.

/doc_static/6.0/_images/tech_arch.png

客户端

OpenERP 的逻辑实在服务器一段配置的。客户端是很简单的,它是仅用于POST的数据(forms, lists, trees)并且把结果发回服务器。新功能的更新和加入并不需要客户端的升级,这使得OpenERP更容易维护.

客户端并不明白POST的内容。即使像点击打印图标的行动时发送到服务器并且询问如何作出反应.

客户端的操作时很简单的,当客户发出一个动作(保存一个表格、打开一个目录、打印…)它发送动作到服务器。然后服务器执行客户端的请求并将结果发送回来.

下面是三种行为;

  • Open a window (form or tree)

  • Print a document

  • Execute a wizard

Python

通过 xml-rpc 获取数据

代码示例
  • 创建一个合伙人和他的地址

import xmlrpclib

username = 'admin' #the user
pwd = 'admin'      #the password of the user
dbname = 'terp'    #the database

# Get the uid
sock_common = xmlrpclib.ServerProxy ('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)

#replace localhost with the address of the server
sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')

partner = {
   'name': 'Fabien Pinckaers',
   'lang': 'fr_FR',
}

partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'create', partner)

address = {
   'partner_id': partner_id,
   'type' : 'default',
   'street': 'Chaussée de Namur 40',
   'zip': '1367',
   'city': 'Grand-Rosière',
   'phone': '+3281813700',
   'fax': '+3281733501',
}

address_id = sock.execute(dbname, uid, pwd, 'res.partner.address', 'create', address)
  • 查询业务伙伴

    args = [('vat', '=', 'ZZZZZZ')] #query clause
    ids = sock.execute(dbname, uid, pwd, 'res.partner', 'search', args)
    
  • 读取业务伙伴数据

    fields = ['name', 'active', 'vat', 'ref'] #fields to read
    data = sock.execute(dbname, uid, pwd, 'res.partner', 'read', ids, fields) #ids is a list of id
    
  • 更新业务伙伴数据

    values = {'vat': 'ZZ1ZZZ'} #data to update
    result = sock.execute(dbname, uid, pwd, 'res.partner', 'write', ids, values)
    
  • 删除业务伙伴

    # ids : list of id
    result = sock.execute(dbname, uid, pwd, 'res.partner', 'unlink', ids)
    

PHP

JAVA

Download the XML-RPC framework for PHP

下载 XML-RPC PHP Library

windows / linux: download the xml-rpc framework for php from http://phpxmlrpc.sourceforge.net/ The latest stable release is version 2.2 released on February 25, 2007

配置 PHP XML-RPC Library

Download the xml-rpc framework for java from http://ws.apache.org/xmlrpc/ The latest stable release is version 3.1 released on August 12, 2007. All OpenERP errors throw exceptions because the framework allows only an int as the error code where OpenERP returns a string.

  • 获取OpenERP帐套列表

function connect() {
   var $user = 'admin';
   var $password = 'admin';
   var $dbname = 'db_name';
   var $server_url = 'http://localhost:8069/xmlrpc/';


   if(isset($_COOKIE["user_id"]) == true)  {
       if($_COOKIE["user_id"]>0) {
       return $_COOKIE["user_id"];
       }
   }

   $sock = new xmlrpc_client($server_url.'common');
   $msg = new xmlrpcmsg('login');
   $msg->addParam(new xmlrpcval($dbname, "string"));
   $msg->addParam(new xmlrpcval($user, "string"));
   $msg->addParam(new xmlrpcval($password, "string"));
   $resp =  $sock->send($msg);
   $val = $resp->value();
   $id = $val->scalarval();
   setcookie("user_id",$id,time()+3600);
   if($id > 0) {
       return $id;
   }else{
       return -1;
   }
 }
  • 登陆OpenERP

/**
 * $client = xml-rpc handler
 * $relation = name of the relation ex: res.partner
 * $attribute = name of the attribute ex:code
 * $operator = search term operator ex: ilike, =, !=
 * $key=search for
 */

function search($client,$relation,$attribute,$operator,$keys) {
     var $user = 'admin';
     var $password = 'admin';
     var $userId = -1;
     var $dbname = 'db_name';
     var $server_url = 'http://localhost:8069/xmlrpc/';

     $key = array(new xmlrpcval(array(new xmlrpcval($attribute , "string"),
              new xmlrpcval($operator,"string"),
              new xmlrpcval($keys,"string")),"array"),
        );

     if($userId<=0) {
     connect();
     }

     $msg = new xmlrpcmsg('execute');
     $msg->addParam(new xmlrpcval($dbname, "string"));
     $msg->addParam(new xmlrpcval($userId, "int"));
     $msg->addParam(new xmlrpcval($password, "string"));
     $msg->addParam(new xmlrpcval($relation, "string"));
     $msg->addParam(new xmlrpcval("search", "string"));
     $msg->addParam(new xmlrpcval($key, "array"));

     $resp = $client->send($msg);
     $val = $resp->value();
     $ids = $val->scalarval();

     return $ids;
}
  • 查询业务伙伴

<?

include('xmlrpc.inc');

$arrayVal = array(
'name'=>new xmlrpcval('Fabien Pinckaers', "string") ,
'vat'=>new xmlrpcval('BE477472701' , "string")
);

$client = new xmlrpc_client("http://localhost:8069/xmlrpc/object");

$msg = new xmlrpcmsg('execute');
$msg->addParam(new xmlrpcval("dbname", "string"));
$msg->addParam(new xmlrpcval("3", "int"));
$msg->addParam(new xmlrpcval("demo", "string"));
$msg->addParam(new xmlrpcval("res.partner", "string"));
$msg->addParam(new xmlrpcval("create", "string"));
$msg->addParam(new xmlrpcval($arrayVal, "struct"));

$resp = $client->send($msg);

if ($resp->faultCode())

    echo 'Error: '.$resp->faultString();

else

    echo 'Partner '.$resp->value()->scalarval().' created !';

?>
  • 创建业务伙伴

/**
 * $client = xml-rpc handler
 * $relation = name of the relation ex: res.partner
 * $attribute = name of the attribute ex:code
 * $operator = search term operator ex: ilike, =, !=
 * $id = id of the record to be updated
 * $data = data to be updated
 */

function write($client,$relation,$attribute,$operator,$data,$id) {
     var $user = 'admin';
     var $password = 'admin';
     var $userId = -1;
     var $dbname = 'db_name';
     var $server_url = 'http://localhost:8069/xmlrpc/';

     $id_val = array();
     $id_val[0] = new xmlrpcval($id, "int");

     if($userId<=0) {
     connect();
     }

     $msg = new xmlrpcmsg('execute');
     $msg->addParam(new xmlrpcval($dbname, "string"));
     $msg->addParam(new xmlrpcval($userId, "int"));
     $msg->addParam(new xmlrpcval($password, "string"));
     $msg->addParam(new xmlrpcval($relation, "string"));
     $msg->addParam(new xmlrpcval("write", "string"));
     $msg->addParam(new xmlrpcval($id, "array"));
     $msg->addParam(new xmlrpcval($data, "struct"));

     $resp = $client->send($msg);
     $val = $resp->value();
     $record = $val->scalarval();

     return $record;

}

更新业务伙伴数据

JAVA

Download the apache XML-RPC framework for JAVA

下载 JAVA XML-RPC Library

Download the xml-rpc framework for java from http://ws.apache.org/xmlrpc/ The latest stable release is version 3.1 released on August 12, 2007. All OpenERP errors throw exceptions because the framework allows only an int as the error code where OpenERP returns a string.

  • 代码示例

import java.net.URL;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

public Vector<String> getDatabaseList(String host, int port)
{
  XmlRpcClient xmlrpcDb = new XmlRpcClient();

  XmlRpcClientConfigImpl xmlrpcConfigDb = new XmlRpcClientConfigImpl();
  xmlrpcConfigDb.setEnabledForExtensions(true);
  xmlrpcConfigDb.setServerURL(new URL("http",host,port,"/xmlrpc/db"));

  xmlrpcDb.setConfig(xmlrpcConfigDb);

  try {
    //Retrieve databases
    Vector<Object> params = new Vector<Object>();
    Object result = xmlrpcDb.execute("list", params);
    Object[] a = (Object[]) result;

    Vector<String> res = new Vector<String>();
    for (int i = 0; i < a.length; i++) {
    if (a[i] instanceof String)
    {
      res.addElement((String)a[i]);
    }
  }
  catch (XmlRpcException e) {
    logger.warn("XmlException Error while retrieving OpenERP Databases: ",e);
    return -2;
  }
  catch (Exception e)
  {
    logger.warn("Error while retrieving OpenERP Databases: ",e);
    return -3;
  }
}
  • 获取OpenERP帐套列表

import java.net.URL;

import org.apache.commons.lang.StringUtils;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

public int Connect(String host, int port, String tinydb, String login, String password)
{
  XmlRpcClient xmlrpcLogin = new XmlRpcClient();

  XmlRpcClientConfigImpl xmlrpcConfigLogin = new XmlRpcClientConfigImpl();
  xmlrpcConfigLogin.setEnabledForExtensions(true);
  xmlrpcConfigLogin.setServerURL(new URL("http",host,port,"/xmlrpc/common"));

  xmlrpcLogin.setConfig(xmlrpcConfigLogin);

  try {
    //Connect
    params = new Object[] {tinydb,login,password};
    Object id = xmlrpcLogin.execute("login", params);
    if (id instanceof Integer)
      return (Integer)id;
    return -1;
  }
  catch (XmlRpcException e) {
    logger.warn("XmlException Error while logging to OpenERP: ",e);
    return -2;
  }
  catch (Exception e)
  {
    logger.warn("Error while logging to OpenERP: ",e);
    return -3;
  }
}
  • 登陆

    TODO
    
  • 查询业务伙伴

    TODO
    
  • 创建业务伙伴

    TODO
    

更新业务伙伴

Python 代码示例

import xmlrpclib

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')
uid = 1
pwd = 'demo'

partner = {
    'title': 'Monsieur',
    'name': 'Fabien Pinckaers',
    'lang': 'fr',
    'active': True,
}

partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'create', partner)

address = {
    'partner_id': partner_id,
    'type': 'default',
    'street': 'Rue du vieux chateau, 21',
    'zip': '1457',
    'city': 'Walhain',
    'phone': '(+32)10.68.94.39',
    'fax': '(+32)10.68.94.39',
}

sock.execute(dbname, uid, pwd, 'res.partner.address', 'create', address)

Example of creation of a partner and their address.

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common')
 UID = sock.login('terp3', 'admin', 'admin')

To get the UID of a user, you can use the following script:

"""
:The login function is under
::    http://localhost:8069/xmlrpc/common
:For object retrieval use:
::    http://localhost:8069/xmlrpc/object
"""
import xmlrpclib

user = 'admin'
pwd = 'admin'
dbname = 'terp3'
model = 'res.partner'

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common')
uid = sock.login(dbname ,user ,pwd)

sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')

# CREATE A PARTNER
partner_data = {'name'.. code-block:: php:'Tiny', 'active':True, 'vat':'ZZZZZ'}
partner_id = sock.execute(dbname, uid, pwd, model, 'create', partner_data)

# The relation between res.partner and res.partner.category is of type many2many
# To add  categories to a partner use the following format:
partner_data = {'name':'Provider2', 'category_id': [(6,0,[3, 2, 1])]}
# Where [3, 2, 1] are id fields of lines in res.partner.category

# SEARCH PARTNERS
args = [('vat', '=', 'ZZZZZ'),]
ids = sock.execute(dbname, uid, pwd, model, 'search', args)

# READ PARTNER DATA
fields = ['name', 'active', 'vat', 'ref']
results = sock.execute(dbname, uid, pwd, model, 'read', ids, fields)
print results

# EDIT PARTNER DATA
values = {'vat':'ZZ1ZZ'}
results = sock.execute(dbname, uid, pwd, model, 'write', ids, values)

# DELETE PARTNER DATA
results = sock.execute(dbname, uid, pwd, model, 'unlink', ids)

CRUD(创建/读取/更新/删除)代码示例:

  1. PRINT(打印) 示例代码:

  2. PRINT INVOICE

  3. IDS is the invoice ID, as returned by:

import time
import base64
printsock = xmlrpclib.ServerProxy('http://server:8069/xmlrpc/report')
model = 'account.invoice'
id_report = printsock.report(dbname, uid, pwd, model, ids, {'model': model, 'id': ids[0], 'report_type':'pdf'})
time.sleep(5)
state = False
attempt = 0
while not state:
    report = printsock.report_get(dbname, uid, pwd, id_report)
    state = report['state']
    if not state:
    time.sleep(1)
    attempt += 1
    if attempt>200:
    print 'Printing aborted, too long delay !'

    string_pdf = base64.decodestring(report['result'])
    file_pdf = open('/tmp/file.pdf','w')
    file_pdf.write(string_pdf)
    file_pdf.close()

PHP Example

This example shows how to insert a new partner using PHP. It uses the phpxmlrpc library, available on sourceforge.

<?

    include('xmlrpc.inc');

    $arrayVal = array(
    'name'=>new xmlrpcval('Fabien Pinckaers', "string") ,
    'vat'=>new xmlrpcval('BE477472701' , "string")
    );

    $client = new xmlrpc_client("http://localhost:8069/xmlrpc/object");

    $msg = new xmlrpcmsg('execute');
    $msg->addParam(new xmlrpcval("dbname", "string"));
    $msg->addParam(new xmlrpcval("3", "int"));
    $msg->addParam(new xmlrpcval("demo", "string"));
    $msg->addParam(new xmlrpcval("res.partner", "string"));
    $msg->addParam(new xmlrpcval("create", "string"));
    $msg->addParam(new xmlrpcval($arrayVal, "struct"));

    $resp = $client->send($msg);

    if ($resp->faultCode())

        echo 'Error: '.$resp->faultString();

    else

        echo 'Partner '.$resp->value()->scalarval().' created !';

    ?>

Here is an example on how to insert a new partner using PHP. This example makes use the phpxmlrpc library, available on sourceforge.

Perl 代码示例

#!c:/perl/bin/perl
# 17-02-2010
# OpenERP XML RPC communication example
# Todor Todorov <todorov@hp.com> <tttodorov@yahoo.com>

use strict;
use Frontier::Client;
use Data::Dumper;

my($user) = 'admin';
my($pw) = 'admin';
my($db) = 'put_your_dbname_here';
my($model) = 'res.partner';

#login
my $server_url = 'http://localhost:8069/xmlrpc/common';
my $server = Frontier::Client->new('url' => $server_url);
my $uid = $server->call('login',$db,$user,$pw);

print Dumper($uid);

my $server_url = 'http://localhost:8069/xmlrpc/object';
my $server = Frontier::Client->new('url' => $server_url);

print Dumper($server);

#
# CREATE A PARTNER
#
my $partner_data = {'name'=>'MyNewPartnerName',
                  'active'=> 'True',
          'vat'=>'ZZZZZ'};
my $partner_id = $server->call('execute',$db, $uid, $pw, $model, 'create', $partner_data);

print Dumper($partner_id);

#
# SEARCH PARTNERS
#
my $query = [['vat', '=', 'ZZZZZ']];

print Dumper($query);

my $ids = $server->call('execute',$db, $uid, $pw, $model, 'search', $query);

print Dumper($ids);


#Here waiting for user input
#OpenERP interface my be checked if partner is shown there

print $/."Check OpenERP if partner is inserted. Press ENTER".$/;
<STDIN>;

#
# DELETE PARTNER DATA
#
my $results = $server->call('execute',$db, $uid, $pw, $model, 'unlink', $ids);

print Dumper($results);

Here is an example in Perl for creating, searching and deleting a partner.