2013-08-20 77 views

回答

11

Tornado帶有同步和異步HTTP客戶端。你可以找到文檔here

下面是上面鏈接的頁面採取了同步的例子:

from tornado import httpclient 
http_client = httpclient.HTTPClient() 
try: 
    response = http_client.fetch(url) 
    print(response.body) 
except httpclient.HTTPError as e: 
    print("Error:", e) 
http_client.close() 

如果您想保存結果輸出到磁盤,然後而不是打印的數據,將其寫入到文件中。需要注意的是,即使在Python 3,龍捲風返回響應主體爲字符串:

with open(output_file_name) as f: 
    f.write(response.body) 

當然,如果響應數據是非常大的,你要下載的文件塊,並寫入到磁盤上the-飛(see here)。最後,如果你由於某種原因不受Tornado限制,我會強烈建議使用requests庫(或異步調用grequests)。

編輯: 要成爲一個靜態文件的下載,做這樣的事情在你的處理器的get

def get(self): 
    file_name = 'file.ext' 
    buf_size = 4096 
    self.set_header('Content-Type', 'application/octet-stream') 
    self.set_header('Content-Disposition', 'attachment; filename=' + file_name) 
    with open(file_name, 'r') as f: 
     while True: 
      data = f.read(buf_size) 
      if not data: 
       break 
      self.write(data) 
    self.finish() 

您可能會或可能不會有在Python 3字節/串問題

+0

謝謝回覆。但我的問題是,例如,如果我是最終用戶。我訪問過example.com網站,如果我點擊下載按鈕,那麼文件需要在各自的瀏覽器中下載。 – dhana

+0

啊,我想知道你爲什麼說「通過網絡瀏覽器」,但駁回它。 –