簡體   English   中英

帶有Tornado的Python:如何在異步函數中獲取獲取響應?

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

我正在嘗試創建一個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

但我有相同的結果:(

再次編輯

我已經成功運行了異步類...但是沒有繼承的對象自身。 我是那樣做的:

@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,並且不確定在定義類時我在這里缺少什么。 調試時,我可以看到self的內容非常“瘦”。請讓我知道我在這里做錯了什么。

謝謝!

只能從其他異步函數中調用異步函數。 您必須像這樣調用_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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM