当客户端断开连接时,Tornado不会自动关闭请求处理程序。但是,您可以重写
on_connection_close以在客户端断开时收到警报,这将使您最终取消连接。上下文管理器(或装饰器)可用于处理设置超时以处理请求。用于
tornado.ioloop.IOLoop.add_timeout安排一些方法,该方法会使请求
timeout作为
__enter__上下文管理器的一部分超时,然后
__exit__在上下文管理器的块中取消该回调。这是一个演示这两个想法的示例:
import timeimport contextlibfrom tornado.ioloop import IOLoopimport tornado.webfrom tornado import gen@gen.coroutinedef async_sleep(timeout): yield gen.Task(IOLoop.instance().add_timeout, time.time() + timeout)@contextlib.contextmanagerdef auto_timeout(self, timeout=2): # Seconds handle = IOLoop.instance().add_timeout(time.time() + timeout, self.timed_out) try: yield handle except Exception as e: print("Caught %s" % e) finally: IOLoop.instance().remove_timeout(handle) if not self._timed_out: self.finish() else: raise Exception("Request timed out") # Don't continue on passed this pointclass TimeoutableHandler(tornado.web.RequestHandler): def initialize(self): self._timed_out = False def timed_out(self): self._timed_out = True self.write("Request timed out!n") self.finish() # Connection to client closes here. # You might want to do other clean up here.class MainHandler(TimeoutableHandler): @gen.coroutine def get(self): with auto_timeout(self): # We'll timeout after 2 seconds spent in this block. self.sleeper = async_sleep(5) yield self.sleeper print("writing") # get will abort before we reach here if we timed out. self.write("heyn") def on_connection_close(self): # This isn't the greatest way to cancel a future, since it will not actually # stop the work being done asynchronously. You'll need to cancel that some # other way. Should be pretty straightforward with a DB connection (close # the cursor/connection, maybe?) self.sleeper.set_exception(Exception("cancelled"))application = tornado.web.Application([ (r"/test", MainHandler),])application.listen(8888)IOLoop.instance().start()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)