最简单的创建Python服务器(XML-RPC Server)的方法是什么?它会在空闲后关闭自己?
我想这样做,但我不知道该怎么做todo:
from SimpleXMLRPCServer import SimpleXMLRPCServer
# my_paths variable
my_paths = []
# Create server
server = SimpleXMLRPCServer(("localhost", 7789))
server.register_introspection_functions()
# TODO: set the timeout
# TODO: set a function to be run on timeout
class MyFunctions:
def add_path(paths):
for path in paths:
my_paths.append(path)
return "done"
def _dispatch(self, method, params):
if method == 'add_path':
# TODO: reset timeout
return add_path(*params)
else:
raise 'bad method'
server.register_instance(MyFunctions())
# Run the server's main loop
server.serve_forever()
我还尝试在示例here之后探索signal.alarm()
,但它不会在Windows下向我投掷AttributeError: 'module' object has no attribute 'SIGALRM'
。
感谢。
答案 0 :(得分:1)
您可以创建自己的扩展SimpleXMLRPCServer
的服务器类,以便在空闲时关闭。
class MyXMLRPCServer(SimpleXMLRPCServer):
def __init__(self, addr):
self.idle_timeout = 5.0 # In seconds
self.idle_timer = Timer(self.idle_timeout, self.shutdown)
self.idle_timer.start()
SimpleXMLRPCServer.__init__(self, addr)
def process_request(self, request, client_address):
# Cancel the previous timer and create a new timer
self.idle_timer.cancel()
self.idle_timer = Timer(self.idle_timeout, self.shutdown)
self.idle_timer.start()
SimpleXMLRPCServer.process_request(self, request, client_address)
现在,您可以使用此类来创建服务器对象。
# Create server
server = MyXMLRPCServer(("localhost", 7789))
server.register_introspection_functions()