简体   繁体   中英

Python with Tornado: How to get fetch response in async functions?

I'm trying to create a Python script which running Tornado Async http client with fetch and trying to get the response and print the response.body to the screen.

my class code is:

class MyAsyncHTTPClient(httpclient.AsyncHTTPClient):

    @gen.coroutine
    def _fetch(self, url):

        print('send Asynchronous request ...['+url+"]   ")

        http_response = yield gen.Task(self.fetch, url)
        print(http_response.body)

        print('got Asynchronous response !!'+str(http_response))

        raise gen.Return(http_response.body)  

and I'm calling it this way:

async_http_client = MyAsyncHTTPClient()
res_body = async_http_client._fetch(url)

The issue is that I'm not sure how to deal with this code to get the returned value once it's ready. can you please help? Thanks!

Editing

I have also tried implementing this function like:

class MyAsyncHTTPClient(httpclient.AsyncHTTPClient):
    @gen.coroutine
    def _fetch(self, url):
        print('send Asynchronous request ...['+url+"]   "+str(self))
        http_response = yield self.fetch(url)
        print('got Asynchronous response !!')
        return http_response.body

But I'm having the same results :(

Editing again

I have succeeded running the async class...but without the inherited object self. I did it like that:

@gen.coroutine
def _fetch_async(self, url):
    print('send Asynchronous request ...[' + url + "]   ")
    http_response = yield httpclient.AsyncHTTPClient().fetch(url)
    #http_response = yield self.fetch(url)
    print('got Asynchronous response !!')
    return http_response.body

and it worked fine. The issue is that I need to use the inherited object self, and I'm not sure what am I missing here when defining the class. When debugging I can see that self is very "thin" with its content.. Please let me know what am I doing wrong here.

Thanks!

Asynchronous functions can only be called from other asynchronous functions. You must call _fetch like this:

@gen.coroutine
def f():
    async_http_client = MyAsyncHTTPClient()
    res_body = yield async_http_client._fetch(url)

If you're not doing this in the context of a tornado server, the best way to call a coroutine from your __main__ block is like this:

tornado.ioloop.IOLoop.current().run_sync(f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM