2012-10-08 155 views
1

創建一個在某個時間空閒後自動關閉的Python服務器(XML-RPC服務器)最簡單的方法是什麼?Python服務器在閒置一段時間後自動關閉

我當時就想,像這樣做,但我不知道在待辦事項的事:

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()下面的例子here但它不會在Windows下運行扔給我AttributeError: 'module' object has no attribute 'SIGALRM'

謝謝。

回答

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() 
相關問題