用Python实现一个XML-RPC服务器

一个简单的Server

~~~~~~~~~~~~~~~~~~~~~~ server.py ~~~~~~~~~~~~~~~~~~~~~~
from SimpleXMLRPCServer import SimpleXMLRPCServer
import logging
import os
# Set up logging
logging.basicConfig(level=logging.DEBUG)
server = SimpleXMLRPCServer((’localhost’, 9000), logRequests=True)
# Expose a function
def list_contents(dir_name):
  logging.debug(’list_contents(%s)’, dir_name)
  return os.listdir(dir_name)

server.register_function(list_contents)
try:
  print ’Use Control-C to exit’
  server.serve_forever()
except KeyboardInterrupt:
print ’Exiting’

~~~~~~~~~~~~~~~~~~~~~~ client.py ~~~~~~~~~~~~~~~~~~~~~~
proxy = xmlrpclib.ServerProxy(’http://localhost:9000’)
print proxy.list_contents(’/tmp’)

别名

from SimpleXMLRPCServer import SimpleXMLRPCServer
import os
server = SimpleXMLRPCServer((’localhost’, 9000))
# Expose a function with an alternate name
def list_contents(dir_name):
  return os.listdir(dir_name)
server.register_function(list_contents, ’dir’)
try:
  print ’Use Control-C to exit’
  server.serve_forever()
except KeyboardInterrupt:
  print ’Exiting’

~~~~~~~~~~~~~~~~~~~~~~ client.py ~~~~~~~~~~~~~~~~~~~~~~
proxy = xmlrpclib.ServerProxy(’http://localhost:9000’)
print ’dir():’, proxy.dir(’/tmp’)
print ’list_contents():’, proxy.list_contents(’/tmp’)

Dotted Names

from SimpleXMLRPCServer import SimpleXMLRPCServer
import os

server = SimpleXMLRPCServer((’localhost’, 9000), allow_none=True)

server.register_function(os.listdir, ’dir.list’)
server.register_function(os.mkdir, ’dir.create’)
server.register_function(os.rmdir, ’dir.remove’)

try:
  print ’Use Control-C to exit’
  server.serve_forever()
except KeyboardInterrupt:
  print ’Exiting’

~~~~~~~~~~~~~~~~~~~~~~ client.py ~~~~~~~~~~~~~~~~~~~~~~
import xmlrpclib
proxy = xmlrpclib.ServerProxy(’http://localhost:9000’)
print ’BEFORE :’, ’EXAMPLE’ in proxy.dir.list(’/tmp’)
print ’CREATE :’, proxy.dir.create(’/tmp/EXAMPLE’)
print ’SHOULD EXIST :’, ’EXAMPLE’ in proxy.dir.list(’/tmp’)
print ’REMOVE :’, proxy.dir.remove(’/tmp/EXAMPLE’)
print ’AFTER :’, ’EXAMPLE’ in proxy.dir.list(’/tmp’)

任意的名字

from SimpleXMLRPCServer import SimpleXMLRPCServer

server = SimpleXMLRPCServer((’localhost’, 9000))

def my_function(a, b):
  return a * b
server.register_function(my_function, ’multiply args’)

try:
  print ’Use Control-C to exit’
  server.serve_forever()
except KeyboardInterrupt:
  print ’Exiting’

~~~~~~~~~~~~~~~~~~~~~~ client.py ~~~~~~~~~~~~~~~~~~~~~~
import xmlrpclib

proxy = xmlrpclib.ServerProxy(’http://localhost:9000’)
print getattr(proxy, ’multiply args’)(5, 5)

暴露对象的方法

By default, register_instance() finds all callable attributes of the instance with names not starting with ‘_‘and registers them with their name.

from SimpleXMLRPCServer import SimpleXMLRPCServer
import os
import inspect

server = SimpleXMLRPCServer((’localhost’, 9000), logRequests=True)

class DirectoryService:
  def list(self, dir_name):
    return os.listdir(dir_name)

server.register_instance(DirectoryService())

try:
  print ’Use Control-C to exit’
  server.serve_forever()
except KeyboardInterrupt:
  print ’Exiting’



~~~~~~~~~~~~~~~~~~~~~~ client.py ~~~~~~~~~~~~~~~~~~~~~~
import xmlrpclib
proxy = xmlrpclib.ServerProxy(’http://localhost:9000’)
print proxy.list(’/tmp’)

暴露对象的方法 + Dotted Names

from SimpleXMLRPCServer import SimpleXMLRPCServer
import os
import inspect

server = SimpleXMLRPCServer((’localhost’, 9000), logRequests=True)

class ServiceRoot:
  pass

class DirectoryService:
  def list(self, dir_name):
    return os.listdir(dir_name)

root = ServiceRoot()
root.dir = DirectoryService()

server.register_instance(DirectoryService())

try:
  print ’Use Control-C to exit’
  server.serve_forever()
except KeyboardInterrupt:
  print ’Exiting’



~~~~~~~~~~~~~~~~~~~~~~ client.py ~~~~~~~~~~~~~~~~~~~~~~
import xmlrpclib
proxy = xmlrpclib.ServerProxy(’http://localhost:9000’)
print proxy.dir.list(’/tmp’)

自定义转发调用

在客户端尝试调用MyService的一个方法时 _dispatch()方法会被调用。在这个方法里,我们加了一个方法的前缀限定,并且要求这个方法必须有一个叫exposed的属性并且值为True。当然你可以随意设计_dispatch的逻辑来满足你的转发需求。

from SimpleXMLRPCServer import SimpleXMLRPCServer
import os
import inspect

server = SimpleXMLRPCServer((’localhost’, 9000), logRequests=True)

def expose(f):
    "Decorator to set exposed flag on a function."
    f.exposed = True
    return f

def is_exposed(f):
    "Test whether another function should be publicly exposed."
    return getattr(f, ’exposed’, False)

class MyService: 
    PREFIX = ’prefix’
    def _dispatch(self, method, params):
        # Remove our prefix from the method name
        if not method.startswith(self.PREFIX + ’.’):
            raise Exception(’method "%s" is not supported’ % method)

        method_name = method.partition(’.’)[2]
        func = getattr(self, method_name)
        if not is_exposed(func):
            raise Exception(’method "%s" is not supported’ % method)

        return func(*params)
    
    @expose
    def public(self):
        return ’This is public’
    
    def private(self):
        return ’This is private’

server.register_instance(MyService())
try:
    print ’Use Control-C to exit’
    server.serve_forever()
except KeyboardInterrupt:
    print ’Exiting’


~~~~~~~~~~~~~~~~~~~~~~ client.py ~~~~~~~~~~~~~~~~~~~~~~
import xmlrpclib
proxy = xmlrpclib.ServerProxy(’http://localhost:9000’) 
print ’public():’, proxy.prefix.public()
try:
    print ’private():’, proxy.prefix.private() 
except Exception, err:
    print ’ERROR:’, err 
try:
    print ’public() without prefix:’, proxy.public() 
except Exception, err:
    print ’ERROR:’, err

Introspection API

有时候我们需要查询服务器有哪些可以调用的接口,这时候这个API就很有用了。
默认这些功能都是被关闭了。你可以通过 register_introspection_functions() 来打开。

from SimpleXMLRPCServer import SimpleXMLRPCServer, list_public_methods 
import os
import inspect

server = SimpleXMLRPCServer((’localhost’, 9000), logRequests=True)
server.register_introspection_functions()

class DirectoryService:
    def _listMethods(self):
        return list_public_methods(self)

    def _methodHelp(self, method):
        f = getattr(self, method) 
        return inspect.getdoc(f)

    def list(self, dir_name):
        """list(dir_name) => [<filenames>]

        Returns a list containing the contents of the named directory. 
        """
        return os.listdir(dir_name)

server.register_instance(MyService())
try:
    print ’Use Control-C to exit’
    server.serve_forever()
except KeyboardInterrupt:
    print ’Exiting’


~~~~~~~~~~~~~~~~~~~~~~ client.py ~~~~~~~~~~~~~~~~~~~~~~
import xmlrpclib
proxy = xmlrpclib.ServerProxy(’http://localhost:9000’) 
for method_name in proxy.system.listMethods():
    print ’=’ * 60
    print method_name
    print ’-’ * 60
    print proxy.system.methodHelp(method_name)
    print

多线程

这个SimpleXMLRPCServer是单任务的,即阻塞式。整成非阻塞式也非常方便:

from SimpleXMLRPCServer import SimpleXMLRPCServer
import SocketServer
class AsyncXMLRPCServer(SocketServer.ThreadingMixIn, SimpleXMLRPCServer):
    pass

server = AsyncXMLRPCServer(SERVER_URL, allow_none=True)

编码的坑

unicode中ASCII码低于空格的(比如这个黑桃字符♠️),在进行XML中传输时,客户端会抛出解析失败的错误:
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 9004, column 46
所以,要么需要对字符串进行一个safe check(将所有ASCII码低于空格的转成空格),要么转用其他协议传输(比如json)。

RPC的设计原则

一个良好的RPC系统设计主要由以下几个独立的模块组成:

  1. 数据结构 (requests/response/errors)
  2. 序列化 (JSON, XML, UI)
  3. 传输 (Socket, TCP/IP, HTTP)
  4. 代理/分发器dispatcher (映射函数调用到RPC)

开源选择

Reference:
https://www.simple-is-better.org/rpc/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,492评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,048评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,927评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,293评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,309评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,024评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,638评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,546评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,073评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,188评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,321评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,998评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,678评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,186评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,303评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,663评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,330评论 2 358

推荐阅读更多精彩内容