xml-rpc 传递对象的python示例代码

1. xml文档

2. 说明

  • 使用docopt,需要注意
    • docopt的命令说明格式,“” xxx ‘’‘’
    • docopt的新增命令,do_打头
  • 使用class,需要注意
    • 类的函数,首参数cls不能少

3. 客户端示例代码

import xmlrpc.client
import sys
import json
import cmd
import urllib
from docopt import docopt, DocoptExit
from colorama import init, Fore
import time
 
class ServerInfo(object):
    """用来定义服务端信息"""
 
    ServerIP = ''
    ServerPort = ''
 
    @classmethod
    def LoadServerInfo(cls):
        cls.ServerIP = '127.0.0.1'
        cls.ServerPort = '5000'
 
    @classmethod
    def GetServerAddr(cls):
        """用来获取服务器地址"""
        return (cls.ServerIP, cls.ServerPort)
 
    @classmethod
    def GetServerUrl(cls):
        if (cls.ServerIP == '') or (cls.ServerPort == ''):
            return ''
        return  xmlrpc.client.ServerProxy('http://' + cls.ServerIP
                    + ':' + cls.ServerPort
                    )
 
 
# 定义一个装饰函数,用来解析命令行
def docopt_cmd(func):
    """
    This decorator is used to simplify the try/except block and pass the result
    of the docopt parsing to the called action.
    """
    def fn(self, arg):
        try:
            opt = docopt(fn.__doc__, arg)
 
        except DocoptExit as e:
            # The DocoptExit is thrown when the args do not match.
            # We print a message to the user and the usage block.
 
            print('Invalid Command!')
            print(e)
            return
 
        except SystemExit:
            # The SystemExit exception prints the usage for --help
            # We do not need to do the print here.
            return
 
        return func(self, opt)
 
    fn.__name__ = func.__name__
    fn.__doc__ = func.__doc__
    fn.__dict__.update(func.__dict__)
    return fn
 
 
class MyInteractive (cmd.Cmd):
    """该类用于提供命令行界面并和服务器进行交互"""
 
    # intro是欢迎界面
    intro = """***********************************
======Welcome to csdn ftz server-client!=======
(type help for a list of commands.)
***********************************"""
 
    # prompt是提示符
    prompt = 'ftz_csdn> '
 
    @docopt_cmd
    def do_plusCaculate(self, arg):
        """Usage:
        plusCaculate --a=<int> --b=<int>

        Options:
            --a=<int>  para 1
            --b=<int>  para 2
        """
        s = ServerInfo().GetServerUrl()
        a = int(arg['--a'])
        b = int(arg['--b'])
        print(s.aPLusb(a,b))
    
    @docopt_cmd
    def do_minusCaculate(self, arg):
        """Usage:
        minusCaculate --a=<int> --b=<int>

        Options:
            --a=<int>  para 1
            --b=<int>  para 2
        """
        s = ServerInfo().GetServerUrl()
        a = int(arg['--a'])
        b = int(arg['--b'])
        print(s.aMinusb(a,b))
 
    @docopt_cmd
    def do_add_user(self, arg):
        """Usage:
        add_user --id=<string> --name=<string> --age=<int> --city=<string>

        Options:
            --id=<string>  para 1
            --name=<string>  para 2
            --age=<int>  para 3 
            --city=<string>  para 4 
        """
        s = ServerInfo().GetServerUrl()
        i = arg['--id']
        name = arg['--name']
        age = int(arg['--age'])
        city = arg['--city']
        user = dict()
        user["name"]=name
        user["age"]=age
        user["city"]=city
        print(s.add_user(i, user))

    @docopt_cmd
    def do_get_user(self, arg):
        """Usage:
        get_user --id=<string>

        Options:
            --id=<string>  para 1
        """
        s = ServerInfo().GetServerUrl()
        i = arg['--id']
        print(s.get_user(i))

    @docopt_cmd
    def do_show_user(self, arg):
        """Usage:
        show_user

        """
        s = ServerInfo().GetServerUrl()
        print(s.show_user())

    @docopt_cmd
    def do_update_user(self, arg):
        """Usage:
        update_user --id=<string> --name=<string> --age=<int> --city=<string>

        Options:
            --id=<string>  para 1
            --name=<string>  para 2
            --age=<int>  para 3 
            --city=<string>  para 4 
        """
        s = ServerInfo().GetServerUrl()
        i = arg['--id']
        name = arg['--name']
        age = int(arg['--age'])
        city = arg['--city']
        user = dict()
        user["name"]=name
        user["age"]=age
        user["city"]=city
        print(s.update_user(i, user))

    @docopt_cmd
    def do_del_user(self, arg):
        """Usage:
        del_user --id=<string> 

        Options:
            --id=<string>  para 1
        """
        s = ServerInfo().GetServerUrl()
        i = arg['--id']
        print(s.del_user(i))

    def do_quit(self, arg):
    	"""Quits out of Interactive Mode."""
    	sys.exit()

    def emptyline(self):
        print('ftz_csdn> ')
 
if __name__ == '__main__':
	#init(autoreset=True)
	ServerInfo().LoadServerInfo()
	MyInteractive().cmdloop()

4. 服务端示例代码

# -*- coding: utf-8 -*-
import json
import os
from urllib import request
import urllib
from socketserver import ThreadingMixIn
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
 
class Processor(object):
    d=dict()

    @classmethod
    def aPLusb(cls,a,b):
        return a+b

    @classmethod
    def aMinusb(cls,a,b):
        return a-b
    
    @classmethod
    def add_user(cls, key, value):
        cls.d[key]=value
        #print(cls.d)
        return key

    @classmethod
    def get_user(cls, key):
        if key in cls.d.keys():
            #print(key)
            return cls.d[key]
        else:
            #print(key)
            #print(type(key))
            return None

    @classmethod
    def update_user(cls, key, value):
        cls.d[key]=value
        return key

    @classmethod
    def del_user(cls, key):
        if key in cls.d.keys():
            cls.d.pop(key)
        #else:
        #    print(type(key), key)
        
        return key

    @classmethod
    def show_user(cls):
        return cls.d
 
class Listener(object):
    """用来描述监听服务器"""
    ListenerIP = ''
    ListenerPort = ''
    Server = ''
 
    # 读取ip和port
    @classmethod
    def LoadListener(cls):
        cls.ListenerIP = '127.0.0.1'
        cls.ListenerPort = 5000 
        print('ListenerAddr: ' + cls.ListenerIP + ':' +  str(cls.ListenerPort))
 
        # 指定访问RPC服务器的URL前缀
        class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ('/RPC2',)
 
        # 创建服务器
        class MyXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
            daemon_threads =True
 
        cls.Server = MyXMLRPCServer((cls.ListenerIP, cls.ListenerPort),
         requestHandler=RequestHandler, allow_none=True)
 
        # 支持列出服务器支持的所有方法
        cls.Server.register_introspection_functions()
 
    # 注册RPC函数 
    @classmethod
    def RegisterFunction(cls, Func, FuncDesc):
        cls.Server.register_function(Func, FuncDesc)
 
    # 启动XMLRPC服务器 
    @classmethod
    def StartListener(cls):
        cls.Server.serve_forever()
 
if __name__ == '__main__':
    # 注册RPC函数
    Listener = Listener()
    Listener.LoadListener()
    Processor = Processor()
   
    # 注册运算服务
    Listener.RegisterFunction(Processor.aPLusb, 'aPLusb')
    Listener.RegisterFunction(Processor.aMinusb, 'aMinusb')
   
    # 注册对象服务
    Listener.RegisterFunction(Processor.add_user, 'add_user')
    Listener.RegisterFunction(Processor.get_user, 'get_user')
    Listener.RegisterFunction(Processor.update_user, 'update_user')
    #Listener.RegisterFunction(Processor.del_user, 'del_user')
    Listener.RegisterFunction(Processor.show_user, 'show_user')
 
    # 开始监听
    Listener.StartListener()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值