第十二章:互联网-xmlrpc.client:XML-RPC的客户库-连接服务器

12.10 xmlrpc.client:XML-RPC的客户库
XML-RPC是一个轻量级远程过程调用协议,建立在HTTP和XML之上。xmlrpclib模块允许Python程序与使用任何语言编写的XML-RPC服务器通信。这一节中的所有例子都使用了xmlrpc_server.py中定义的服务器,可以在源发布包中找到,这里给出这个服务器以供参考。

# xmlrpc_server.py
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.client import Binary
import datetime


class ExampleService:

    def ping(self):
        """Simple function to respond when called
        to demonstrate connectivity.
        """
        return True

    def now(self):
        """Returns the server current date and time."""
        return datetime.datetime.now()

    def show_type(self,arg):
        """Illustrates how types are passed in and out of
        server methods.

        Accepts one argument of any type.

        Returns a tuple with string representation of the value,
        the name of the type,and the value itself.

        """
        return (str(arg),str(type(arg)),arg)

    def raises_exception(self,msg):
        "Always raises a RuntimeError with the message passed in."
        raise RuntimeError(msg)

    def send_back_binary(self,bin):
        """Accepts a single Binary argument, and unpacks and
        repacks it to return it."""
        data = bin.data
        print('send_back_binary({!r})'.format(data))
        response = Binary(data)
        return response


if __name__ == '__main__':
    server = SimpleXMLRPCServer(('localhost',9000),
                                logRequests=True,
                                allow_none=True)
    server.register_introspection_functions()
    server.register_multicall_functions()

    server.register_instance(ExampleService())

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

在这里插入图片描述
12.10.1 连接服务器
要将一个客户端连接到服务器,最简单的方法是实例化一个ServerProxy对象,为它指定服务器的URI。例如,演示服务器在localhost的端口9000上运行。

import xmlrpc.client

server = xmlrpc.client.ServerProxy('http://localhost:9000')
print('Ping:',server.ping())

在这种情况下,服务的ping()方法没有任何参数,它会返回一个布尔值。
运行结果:
在这里插入图片描述
还可以有其他选项支持其他类型的传输以便连接服务器。HTTP和HTTPS已经明确得到支持,二者都提供基本认证。要实现一个新的通信通道,只需要一个新的传输类。例如,可以在SMTP之上实现XML-RPC,这是一个很有意思的训练。

import xmlrpc.client

server = xmlrpc.client.ServerProxy('http://localhost:9000',
                                   verbose=True)
print('Ping:',server.ping())

指定verbose选项会提供调试信息,这对于解决通信错误很有用。
运行结果:
在这里插入图片描述
如果需要其他系统,则可以将默认编码由UTF-8改为其他编码。

import xmlrpc.client

server = xmlrpc.client.ServerProxy('http://localhost:9000',
                                   encoding='ISO-8859-1')
print('Ping:',server.ping())

服务器会自动检测正确的编码。
运行结果:
在这里插入图片描述
allow_none选项会控制Python的None值是自动转换为nil值还是会导致一个错误。

import xmlrpc.client

server = xmlrpc.client.ServerProxy('http://localhost:9000',
                                   allow_none=False)

try:
    server.show_type(None)
except TypeError as err:
    print('ERROR:',err)

server = xmlrpc.client.ServerProxy('http://localhost:9000',
                                   allow_none=True)
print('Allowed:',server.show_type(None))

如果客户不允许None,则会在本地产生一个错误,不过如果未配置允许None,那么也有可能从服务器产生错误。
运行结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值