回调处理异步请求
- 回调
callback
处理异步官方例子
# 导入所需库
from tornado.httpclient import AsyncHTTPClient
def asynchronous_fetch(url, callback): http_client = AsyncHTTPClient() def handle_response(response): callback(response.body) http_client.fetch(url, callback=handle_response)
- 当
http_client
处理请求时http_client.fetch(url, callback=handle_response)
,参数url
是请求的url, 关键字参数callback
传入方法handle_response
此方法即为回调方法, 就是说当http_client
请求完成后才会调用callback=handle_response
中的handle_response
函数. - 请求网络是耗时操作,传入关键字参数
callback
来'表明'这是异步请求, 以此来确定这是异步处理请求
协程处理异步
from tornado import gen
@gen.coroutine
def fetch_coroutine(url): http_client = AsyncHTTPClient() response = yield http_client.fetch(url) raise gen.Return(response.body)
@gen.coroutine
此装饰器代表的是协程, 与关键字yield
搭配使用http_client.fetch(url)
请求网络是耗时操作, 通过关键字yield
来挂起调用, 而当http_client.fetch(url)
请求完成时再继续从函数挂起的位置继续往下执行.raise gen.Return(response.body)
在python3.3以后作用相当于return
, 在python3.3之前作用是返回一个异常值, 跟 返回一个value, 以及python3.3之前generators
不可以return value
, 所以tornado定义了一个特殊的返回值raise gen.Return
.- 在python3.3以后直接用return
回调处理异步请求
- 回调
callback
处理异步官方例子
# 导入所需库
from tornado.httpclient import AsyncHTTPClient
def asynchronous_fetch(url, callback): http_client = AsyncHTTPClient() def handle_response(response): callback(response.body) http_client.fetch(url, callback=handle_response)
- 当
http_client
处理请求时http_client.fetch(url, callback=handle_response)
,参数url
是请求的url, 关键字参数callback
传入方法handle_response
此方法即为回调方法, 就是说当http_client
请求完成后才会调用callback=handle_response
中的handle_response
函数. - 请求网络是耗时操作,传入关键字参数
callback
来'表明'这是异步请求, 以此来确定这是异步处理请求
协程处理异步
from tornado import gen
@gen.coroutine
def fetch_coroutine(url): http_client = AsyncHTTPClient() response = yield http_client.fetch(url) raise gen.Return(response.body)
@gen.coroutine
此装饰器代表的是协程, 与关键字yield
搭配使用http_client.fetch(url)
请求网络是耗时操作, 通过关键字yield
来挂起调用, 而当http_client.fetch(url)
请求完成时再继续从函数挂起的位置继续往下执行.raise gen.Return(response.body)
在python3.3以后作用相当于return
, 在python3.3之前作用是返回一个异常值, 跟 返回一个value, 以及python3.3之前generators
不可以return value
, 所以tornado定义了一个特殊的返回值raise gen.Return
.- 在python3.3以后直接用return