Running an async background task in Tornado

前端 未结 5 1419
北荒
北荒 2020-12-15 06:50

Reading the Tornado documentation, it\'s very clear how to call an async function to return a response:

class GenAsyncHandler(RequestHandler):
    @gen.corou         


        
5条回答
  •  失恋的感觉
    2020-12-15 07:23

    Update: Since Tornado 4.0 (July 2014), the below functionality is available in the IOLoop.spawn_callback method.

    Unfortunately it's kind of tricky. You need to both detach the background task from the current request (so that a failure in the background task doesn't result in a random exception thrown into the request) and ensure that something is listening to the background task's result (to log its errors if nothing else). This means something like this:

    from tornado.ioloop import IOLoop
    from tornado.stack_context import run_in_stack_context, NullContext
    IOLoop.current().add_future(run_in_stack_context(NullContext(), self._background_task),
                                lambda f: f.result())
    

    Something like this will probably be added to tornado itself in the future.

提交回复
热议问题