Can't call result() on futures in tornado

后端 未结 1 438
粉色の甜心
粉色の甜心 2020-12-20 18:10

I want to do some asynchronous HTTP-requests using the python library tornado (version 4.2). I can however not force a future to complete (using result()) since

相关标签:
1条回答
  • 2020-12-20 18:29

    Try to create another Future and use add_done_callback:

    From Tornado documentation

    from tornado.concurrent import Future
    
    def async_fetch_future(url):
        http_client = AsyncHTTPClient()
        my_future = Future()
        fetch_future = http_client.fetch(url)
        fetch_future.add_done_callback(
            lambda f: my_future.set_result(f.result()))
        return my_future
    

    But you still need solve the future with the ioloop, like this:

    # -*- coding: utf-8 -*-
    from tornado.concurrent import Future
    from tornado.httpclient import AsyncHTTPClient
    from tornado.ioloop import IOLoop
    
    
    def async_fetch_future():
        http_client = AsyncHTTPClient()
        my_future = Future()
        fetch_future = http_client.fetch('http://www.google.com')
        fetch_future.add_done_callback(
            lambda f: my_future.set_result(f.result()))
        return my_future
    
    response = IOLoop.current().run_sync(async_fetch_future)
    
    print(response.body)
    

    Another way to this, is using tornado.gen.coroutinedecorator, like this:

    # -*- coding: utf-8 -*-
    from tornado.gen import coroutine
    from tornado.httpclient import AsyncHTTPClient
    from tornado.ioloop import IOLoop
    
    
    @coroutine
    def async_fetch_future():
        http_client = AsyncHTTPClient()
        fetch_result = yield http_client.fetch('http://www.google.com')
        return fetch_result
    
    result = IOLoop.current().run_sync(async_fetch_future)
    
    print(result.body)
    

    coroutine decorator causes the function to return a Future.

    0 讨论(0)
提交回复
热议问题