1

我是 XML-RPC 的新手。

#client code
import xmlrpclib
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
x,y = arg1,arg2
print proxy.fun1(x,y)
print proxy.fun2(x,y)

服务器应该做什么:

  1. 加载乐趣1
  2. 注册乐趣1
  3. 返回结果
  4. 卸载乐趣1

然后对 fun2 做同样的事情。

做这个的最好方式是什么?

我已经想出了一种方法来做到这一点,但它听起来“笨拙,牵强和不合常规”。

4

3 回答 3

2

通常,服务器会继续运行 - 所以在开始时注册这两种方法。我不明白你为什么要注销你的函数。服务器保持正常运行并处理多个请求。您可能需要一个shutdown()关闭整个服务器的功能,但我看不到取消注册单个功能。

最简单的方法是使用SimpleXMLRPCServer

from SimpleXMLRPCServer import SimpleXMLRPCServer

def fun1(x, y):
    return x + y


def fun2(x, y):
    return x - y

server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(fun1)
server.register_function(fun2)
server.serve_forever()
于 2009-01-30T10:13:08.847 回答
2

如果要动态注册,请注册一个对象的实例,然后在该对象上设置属性。__getattr__如果需要在运行时确定函数,您可以使用类的方法获得更高级的信息。

class dispatcher(object): pass
   def __getattr__(self, name):
     # logic to determine if 'name' is a function, and what
     # function should be returned
     return the_func
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(dispatcher())
于 2009-01-31T20:07:49.690 回答
2

您可以动态注册函数(在服务器启动后):

#Server side code:
import sys
from SimpleXMLRPCServer import SimpleXMLRPCServer

def dynRegFunc(): #this function will be registered dynamically, from the client
     return True 

def registerFunction(function): #this function will register with the given name
    server.register_function(getattr(sys.modules[__name__], str(function)))

if __name__ == '__main__':
    server = SimpleXMLRPCServer((address, port)), allow_none = True)
    server.register_function(registerFunction)
    server.serve_forever()



#Client side code:

 import xmlrpclib

 if __name__ == '__main__':
     proxy = xmlrpclib.ServerProxy('http://'+str(address)+':'+str(port), allow_none = True)

 #if you'd try to call the function dynRegFunc now, it wouldnt work, since it's not registered -> proxy.dynRegFunc() would fail to execute

 #register function dynamically: 
  proxy.registerFunction("dynRegFunc")
 #call the newly registered function
  proxy.dynRegFunc() #should work now!
于 2014-08-08T11:44:29.677 回答