创建在空闲一段时间后自行关闭的Python服务器(XML-RPC服务器)的最简单方法是什么?
我想这样做,但我不知道在待办事项中该怎么做:
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()
我还尝试按照此处的示例探索signal.alarm()
但它不会在 Windows 下运行,向我抛出AttributeError: 'module' object has no attribute 'SIGALRM'
。
谢谢。
您可以创建自己的服务器类来扩展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()