带有Tornado的Python:如何在异步函数中获取获取响应?

时间:2017-12-10 13:16:34

标签: python asynchronous httpclient tornado

我正在尝试创建一个Python脚本,该脚本使用fetch 运行 Tornado Async http客户端,并尝试获取响应并将response.body打印到屏幕上。

我的班级代码是:

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)  

我这样称呼它:

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

问题是我不知道如何处理这段代码以便在准备好后获得返回值。 你能帮忙吗? 谢谢!

修改

我也试过实现这个功能,如:

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

但我的结果相同:(

再次编辑

我已成功运行异步类...但没有继承的对象self。 我这样做了:

@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

它工作正常。 问题是我需要使用继承的对象self,我不确定在定义类时我在这里缺少什么。 调试时我可以看到自己的内容非常“瘦”。 请让我知道我在这里做错了什么。

谢谢!

1 个答案:

答案 0 :(得分:0)

异步函数只能从其他异步函数中调用。您必须像这样致电_fetch

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

如果您未在龙卷风服务器的上下文中执行此操作,则从__main__块调用协同程序的最佳方法是这样的:

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