原文地址:http://www.ibm.com/developerworks/webservices/library/ws-pyth10/index.html



摘要:概括地说,您可以将 XML-RPC 认为是简化的 SOAP。它是允许运行在不同操作系统、不同环境中的软件进行基于Internet 过程调用的规范和一组实现。这种远程过程调用使用 HTTP 作为传输协议,XML 作为编码格式。XML-RPC 的定义尽可能简单,但能够传送、处理和返回复杂的数据结构。

The Python web services developer: XML-RPC for Python

Mike Olson, Principal Consultant, Fourthought, Inc.

Uche Ogbuji (uche@ogbuji.net),
Principal Consultant, Fourthought, Inc.

Summary:  XML-RPC is a simple, lightweight web services technology that predates SOAP. In this installment of the Python web services developer, Mike Olson and Uche Ogbuji examine the XML-RPC facilities in Python.

XML-RPC is the granddaddy of XML web services. It is a simple specification for remote procedure calls (RPC) that uses HTTP as the transport protocol and an XML vocabulary as the message payload. It has become very popular because of its simplicity (the
full specification is less than ten printed pages), and most languages now have standard or readily available XML-RPC implementations. This includes Python, which started bundling xmlrpclib, an XML-RPC implementation by Fredrik Lundh, in version 2.2. Joe Johnston's
IBM developerWorks article "Using XML-RPC for web services" (see Resources) covers the basics of XML-RPC in the first three sections. Start there if you need to review the basic technology. In this article, we will focus on using the Python implementation. You must have Python 2.2. to run the examples in this article.
Also, in the last article, we looked at the relative performance of XML-RPC, SOAP, and other distributed programming technologies. You may want to read that before making major decisions to deploy XML-RPC.

Clients

Writing a Python XML-RPC client is very easy. The module xmlrpclib has all the needed machinery. In order to invoke a remote XML-RPC object, you create a proxy object which forwards requests to the server using XML-RPC. The proxy object looks and feels just
like a regular Python object, and your requests are simple function calls. Listing 1 (currtime.py) uses XML-RPC to get the current time from the UserLand server (seeResources for more information about this service).

  import xmlrpclib

#Port 80 is the default
server = xmlrpclib.ServerProxy("http://time.xmlrpc.com") currentTimeObj = server.currentTime
currtime = currentTimeObj.getCurrentTime() print currtime
print currtime.value

What is actually being proxied is the server, which is set up by initializing an instance of theServerProxy class. We pass in the full URL of the remote server (you must include the URL scheme "http://"). Port 80 is the default, as usual. If
the remote server were instead listening on port 8080, we would use "http://time.xmlrpc.com:8080". The server proxy has all the actual remote objects they host as regular attributes, and in this way we get a handle to the remote object namedcurrentTime.
Now we can simply call the method on this proxy object, which returns the current time. The response is of a special XML-RPC type called a DateTime. To get a plain string representation of this object, we use itsvalue attribute.

One important clarification: the idea of distinct proxy objects within the server is really an illusion. XML-RPC allows method names to have periods in them, and it is a common convention to use method names such aspseudo_object.foo, that allows
clients to treat it as a call to a methodfoo on a remote object namedpseudo_object. However, as far as XML-RPC protocol is concerned, this is just a method namedpseudo_object.foo defined on the remote server. You'll see later
on why this distinction is important.

The result of running the script:

$ python currtime.py
<DateTime 20020808T10:43:06 at 81dd0ec>
20020808T10:43:06

DataType, as we've seen, is one special type used in Python's XML-RPC implementation based on the specification. It must be used for input and output to XML-RPC systems if they require such types. In other words, if a remote function takes a DateTime
argument, you cannot send it a string such as "20020808T10:43:06". You would first construct an instance of the DateTime class. For instance:

datetime_arg = xmlrpclib.DateTime("20020808T10:43:06")
remote_obj.method(datetime_arg)

There are a few other such special types. Boolean and Binary are basic data types, and the specialFault object is used for exception handling.Boolean might be going away since Python 2.3 introduces a native
boolean typebool.Binary is distinct from strings in that it does not restrict what bytes can be transmitted. The other XML-RPC types are represented by native Python objects, with lists and tuples standing in for arrays and dictionaries
for structures. One important warning is about character encodings. A much-criticized limitation of XML-RPC is that it only supports the transmission of ASCII strings (or binary buffers). It offers no character encoding support at all.Listing
2
tries to use Useful Inc's sample string echo service (which simply takes a string and returns the same string).

  import xmlrpclib

server = xmlrpclib.ServerProxy("http://xmlrpc.usefulinc.com/demo/server.php")

eg_obj = server.examples
result = eg_obj.stringecho(u"Freude, schönergötterfunken") print unicode(result)

However, if you run it, you will find that the string has been corruptedby the remote server:

$ python stringecho.py
Freude, schnergtterfunken

This is because although Python supports Unicode strings, the remotesystem does not. XML-RPC oficially only specifies ASCII as a stringencoding, a well-known and unfortunate limitation.

The first attractive solution to encode to UTF-8, unfortunately, will not work since UTF-8 does not "fit" into the 7-bit ASCII range. One could use is to use UTF-7, which does fit into ASCII range, but this is a less common and more verbose encoding. To
use UTF-7, replace the relevant line with:

result = eg_obj.stringecho(u"Freude,schönergötterfunken".encode("utf-7"))

resulting in:

$ python stringecho.py
Freude, sch+APY-ne g+APY-tterfunken

This is unfortunate because it distorts the value being sent remotely, and requires an out-of-band understanding between the parties that strings being passed are in UTF-7 encoding. If this sort of communication can be established between the parties, the
server could also accept binary objects rather than strings, which means that UTF-8 could be used. But this is just hacking around a glaring fault in the protocol itself, and perhaps a good reason to consider SOAP, which is properly internationalized.

Handling faults

When the server needs to signal an error, it does so using an XML-RPC fault. This is interpreted in Python using a special exception object which gives a fault code and descriptive string.Listing
3
(getstate.py) uses an XML-RPC service for returning a state name according to a number passed in which represents the index of the state in alphabetic order. We purposefully use a bogus value of-1 which causes the server to raise a fault:

  import xmlrpclib

server = xmlrpclib.ServerProxy("http://xmlrpc.usefulinc.com/demo/server.php")

eg_obj = server.examples
try:
result = eg_obj.getStateName(-1)
except xmlrpclib.Fault, fault:
print fault.faultCode
print fault.faultString

Which results in:

$ python getstate.py
800
I don't have a state for the index '-1'

If it is the XML-RPC machinery rather than the service itself that encounters a problem (for instance, you give it a URL that cannot be reached), aProtocolError exception object is raised rather than aFault object.

Back to top

XML-RPC servers

Python also comes with SimpleXMLRPCServer, a module for implementing XML-RPC servers. You can register functions or instances with an instance of theSimpleXMLRPCServer class in the module of the same name, in order to expose XML-RPC
services. The most straightforward way is to just write an instance with methods that do what you need, and then register this instance. However, in this case, method names cannot have periods, and so the trickery we discussed above to make things appear as
if there are multiple objects represented by the server is unavailable. The effect of this will become clear soon, but first of all, let us create a calendar server such as the one we've been using to demonstrate SOAP servers.Listing
4
(calserver.py) is the XML-RPC calendar server implementation:

  import calendar, SimpleXMLRPCServer

#The server object
class Calendar:
def getMonth(self, year, month):
return calendar.month(year, month) def getYear(self, year):
return calendar.calendar(year) calendar_object = Calendar()
server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8888))
server.register_instance(calendar_object) #Go into the main listener loop
print "Listening on port 8888"
server.serve_forever()

The class Calendar implements the methods we wish to expose. They take numbers and return strings. We create an instance of this object and then an instance of the XML-RPC server class, with which we register the calendar instance. This now
makes the methods getMonth and getYear available on the server. Remember that Python is dynamically typed, and that you will want to add type-checking code to the methods in most cases. Of course Python's rich expressiveness makes
this a breeze, and also means that you can easily do more sophisticated type checking than most languages allow. In the main code, we create a server object, giving it a tuple representing the listening address and port. The address can be a host name or IP
address. Finally, we put this server into its main loop, which is only broken when an operating system signal interrupts it, such as when the user presses CTRL-C. Open up a separate console and run the server script.

To test the server, we write a simple client in Listing 5 (calclient.py):

  import xmlrpclib

server = xmlrpclib.ServerProxy("http://localhost:8888")

month = server.getMonth(2002, 8)
print month

And here you can see the effect of our not having a period in the method names. Rather than first of all obtaining a pseudo-object from the server (which really just represents an abstraction of the part of the method name before the period), we simply call
the method on the server proxy itself. The resulting output is:

$ python calclient.py
August 2002
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Back to top

Conclusion

XML-RPC is simpler than SOAP, and is very popular in open-source projects. It is an essential toolkit for any language or framework to offer these days, and so Python's new XML-RPC modules are a welcome addition. However, it does have its weaknesses, chief
of which is its support for character encodings, which shows an appalling bias towards English which seems out of place in these days when the importance of internationalization is well understood.

In the next installment we shall examine Python tools for another web services interface that has gained widespread popularity: RDF site summary (RSS).

Resources

About the authors

Mike Olson is a consultant and co-founder of Fourthought Inc., a software vendor and consultancy specializing in XML solutions for enterprise knowledge management applications. Fourthought develops4Suite, an open source platform for XML middleware. You can contact Mr.
Olson atmike.olson@fourthought.com.

Uche Ogbuji is a consultant and co-founder of Fourthought Inc., a software vendor and consultancy specializing in XML solutions for enterprise knowledge management applications. Fourthought develops4Suite, open source platforms for XML middleware.Mr. Ogbuji is a Computer
Engineer and writer born in Nigeria, living and working in Boulder, Colorado, USA. You can contact Mr. Ogbuji atuche@ogbuji.net.

The Python web services developer: XML-RPC for Python的更多相关文章

  1. Python Web-第五周-Web Services and XML(Using Python to Access Web Data)

    1.Web Service Overview 1.Data on the Web Python Dictionary 和 Java HashMap间需要建立一个桥梁,可以用XML或是JSON 2.XM ...

  2. 《Using Python to Access Web Data》 Week5 Web Services and XML 课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week5 Web Services and XML 13.1 Data on the ...

  3. 基于soap 的 python web services 服务开发指南

    文章大纲 序言 相关概念 SOA web services SOAP WSDL UDDI 环境搭建 我们使用 python 3.6 这个较新python 版本 服务端开发 客户端开发 suds-jur ...

  4. Web Services 中XML、SOAP和WSDL的一些必要知识

    Web Services 是由xml来定义数据格式的,通过SOAP协议在各个系统平台中传输,那么接下来讨论下SOAP和WSDL的各自作用. SOAP和WSDL对Web Service.WCF进行深入了 ...

  5. Java EE (3) -- Java EE 6 Web Services Developer Certified Expert(1z0-897)

    Create an SOAP web service in a servlet container Create a RESTful web service in a servlet containe ...

  6. python三大web框架Django,Flask,Flask,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架

    Python几种主流框架 从GitHub中整理出的15个最受欢迎的Python开源框架.这些框架包括事件I/O,OLAP,Web开发,高性能网络通信,测试,爬虫等. Django: Python We ...

  7. Django,Flask,Tornado三大框架对比,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架

    Django 与 Tornado 各自的优缺点Django优点: 大和全(重量级框架)自带orm,template,view 需要的功能也可以去找第三方的app注重高效开发全自动化的管理后台(只需要使 ...

  8. 用jersey写 java restfull web services 输出xml格式数据

    1 logic package com.toic.rest; import com.toic.model.Folder; import java.util.logging.Logger; import ...

  9. xml rpc SimpleXMLRPCServer [python]

    SimpleXMLRPCServe 其实里面xml的概念不是很强,主要是rpc !不用关心什么xml . rpc 是就是远程调用,把函数什么的放到远程服务器上,本地调用就行了.用 SimpleXMLR ...

随机推荐

  1. sql for xml 嵌套

    找很久.原来差一个ELEMENTS 关键字. 想到哪里插入子节点.就直接写一条语句,加一个ELEMENTS. 为什么baidu这么就都找不到.到处都是转来转去的东西.郁闷. select h.*,(s ...

  2. mysql 查询执行的流程

    1.客户端发送一个请求给服务器.2.服务器先检查查询缓存,命中了缓存,直接返回缓存中的数据,否则进入下一个阶段.3.服务器进行sql解析,预处理,再由优化器生成对应的执行计划.4.mysql根据执行计 ...

  3. 1503 - A PRIMARY KEY must include all columns in the table's partitioning function

    1503 - A PRIMARY KEY must include all columns in the table's partitioning function 错误的原因:表的主键字段必须包含分 ...

  4. FSL安装

    本文介绍如何安装医学图像处理软件fsl. 安装环境:Win8和Ubuntu 14.04 LTS(双系统和虚拟机皆可) 1. 安装ubuntu 14.04 LTS 2. 打开终端,设置ip代理:expo ...

  5. Vbs脚本经典教材(转)

    Vbs脚本经典教材(最全的资料还是MSDN) —为什么要使用Vbs? 在Windows中,学习计算机操作也许很简单,但是很多计算机工作是重复性劳动,例如你每周也许需要对一些计算机文件进行复制.粘贴.改 ...

  6. js 中文乱码

    js合成url时,如果参数是中文,传到struts2中会乱码,解决办法如下:1.js文件中使用encodeURI()方法(必须套两层).login_name = encodeURI(encodeURI ...

  7. 自己学习smarty的一些代码 和记录

    http://www.yiibai.com/smarty/smarty_install.html  手册可以看这里 index.tpl <!DOCTYPE html> <html&g ...

  8. 深入理解PHP原理之变量作用域

    26 Aug 08 深入理解PHP原理之变量作用域(Scope in PHP)   作者: Laruence(   ) 本文地址: http://www.laruence.com/2008/08/26 ...

  9. 垂直的seekbar

    看下效果: 1 package org.qianyukun.core.views; import android.content.Context; import android.graphics.Ca ...

  10. hdu----(3068)最长回文(manacher)

    最长回文 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submis ...