我是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)
服务器应该做什么:
然后和fun2一样。
这样做的最佳方式是什么?
我已经找到了一种方法来做到这一点,但它听起来“笨拙,牵强,无声”。
答案 0 :(得分: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()
答案 1 :(得分:1)
如果要进行动态注册,请注册对象的实例,然后在该对象上设置属性。如果需要在运行时确定函数,则可以使用类的__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())
答案 2 :(得分:1)
您可以动态注册函数(在服务器启动后):
#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!