Ben*_*hom 11
Tornado同时带有同步和异步HTTP客户端.你可以在这里找到文档.
这是从上面链接的页面获取的同步示例:
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()
Run Code Online (Sandbox Code Playgroud)
如果要将结果输出保存到磁盘,而不是打印数据,请将其写入文件.请注意,即使在Python 3中,Tornado也会将响应主体作为字符串返回:
with open(output_file_name) as f:
f.write(response.body)
Run Code Online (Sandbox Code Playgroud)
当然,如果响应数据非常大,您将需要以块的形式下载文件并即时写入磁盘(请参阅此处).
最后,如果你因某些原因没有受到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()
Run Code Online (Sandbox Code Playgroud)
Python 3中可能有也可能没有字节/字符串问题.
| 归档时间: |
|
| 查看次数: |
7039 次 |
| 最近记录: |