【问题标题】:How can tornado catch interrupt of client龙卷风如何捕捉客户端的中断
【发布时间】:2019-08-23 08:19:30
【问题描述】:

当用户中断他对我的 tornado HTTP 服务器的请求时,我想处理 tornado(ver = 4.0),但我不知道这个事件何时发生。例如,我启动服务器,并运行 curl 命令来请求它,然后我在请求时中断 curl。请帮忙,谢谢!

这是我的操作

我阅读了文档并找到了on_finish 方法,但是当请求完成时会调用该方法。

# coding=u8
import time
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        print('Start %s.'%time.strftime('%F %H:%M:%S'))
        time.sleep(5)
        self.write('ok.')
        print('Finish %s.'%time.strftime('%F %H:%M:%S'))

    def on_finish(self):
        """Called after the end of a request.
        Override this method to perform cleanup, logging, etc.
        This method is a counterpart to `prepare`.  ``on_finish`` may
        not produce any output, as it is called after the response
        has been sent to the client.
        """
        print('Cancelled %s.'%time.strftime('%F %H:%M:%S'))

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

在处理请求期间,我如何知道客户端何时取消了它的请求?

【问题讨论】:

    标签: http tornado


    【解决方案1】:
    1. 使用on_connection_close()方法检测客户端何时关闭连接。
    2. 不要使用time.sleep,因为它是一个阻塞函数。当您使用阻塞功能时,Tornado 的一些异步功能将不起作用。相反,请使用gen.sleep 之类的非阻塞替代方案。

    例子:

    from tornado import gen
    
    class MainHandler(tornado.web.RequestHandler):
        @gen.coroutine
        def get(self):
            yield gen.sleep(5) # asynchronous sleep
            # ... do something else
    
        def on_connection_close(self):
            print('Cancelled %s.'%time.strftime('%F %H:%M:%S'))
    

    【讨论】:

    • 非常感谢!我的真实代码是同步的,我想捕获取消的请求,然后节省资源。也许我错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多