回調處理異步請求
# 導入所需庫
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
