tornado关于AsyncHTTPClient的使用笔记

先来一段同步的httpclient使用代码

url = 'https://www.baidu.com/'

http_client = HTTPClient()
response = http_client.fetch(url)
print("xu jun test" + str(response.body))

然后是异步调用AsyncHTTPClient:

url = 'https://www.baidu.com/'


async def test():
    http_client = AsyncHTTPClient()
    result = await http_client.fetch(url)
    print(result.body)


if __name__ == '__main__':
    io_loop = ioloop.IOLoop.current()
    io_loop.run_sync(test)

还有一种是通过回调函数的方式使用,注意如果没反应,要在协程中使用

def handle_request(response):
    if response.error:
        print("Error:", response.error)
    else:
        print(response.body)

url = 'https://www.baidu.com/'

http_client = AsyncHTTPClient()
http_client.fetch(url, handle_request)

PS.由于tornado的版本升级较快,网上很多文档和API都过时了.所有有时候直接看源代码,或者找网上的示例代码,会更有效!

原文地址:https://www.cnblogs.com/xujanus/p/8605554.html