简体   繁体   English

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

[英]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. 我正在尝试创建一个Python脚本,该脚本使用fetch运行Tornado Async http客户端,并尝试获取响应并将response.body打印到屏幕上。

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. 问题是我需要使用继承的对象self,并且不确定在定义类时我在这里缺少什么。 When debugging I can see that self is very "thin" with its content.. Please let me know what am I doing wrong here. 调试时,我可以看到self的内容非常“瘦”。请让我知道我在这里做错了什么。

Thanks! 谢谢!

Asynchronous functions can only be called from other asynchronous functions. 只能从其他异步函数中调用异步函数。 You must call _fetch like this: 您必须像这样调用_fetch

@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: 如果您不是在龙卷风服务器的环境中执行此操作,则从__main__块调用协程的最佳方法如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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