Right way to “timeout” a Request in Tornado

前端 未结 2 748
盖世英雄少女心
盖世英雄少女心 2021-01-03 06:24

I managed to code a rather silly bug that would make one of my request handlers run a very slow DB query.

Interesting bit is that I noticed that even long-after si

2条回答
  •  清酒与你
    2021-01-03 07:05

    Another solution to this problem is to use gen.with_timeout:

    import time
    from tornado import gen
    from tornado.util import TimeoutError
    
    
    class MainHandler
    
        @gen.coroutine
        def get(self):
            try:
                # I'm using gen.sleep here but you can use any future in this place
                yield gen.with_timeout(time.time() + 2, gen.sleep(5))
                self.write("This will never be reached!!")
            except TimeoutError as te:
                logger.warning(te.__repr__())
                self.timed_out()
    
        def timed_out(self):
            self.write("Request timed out!\n")
    

    I liked the way handled by the contextlib solution but I'm was always getting logging leftovers.

    The native coroutine solution would be:

    async def get(self):
        try:
            await gen.with_timeout(time.time() + 2, gen.sleep(5))
            self.write("This will never be reached!!")
        except TimeoutError as te:
            logger.warning(te.__repr__())
            self.timed_out()
    

提交回复
热议问题