python - Download functionality in Tornado? -


i new tornado web framework. can 1 tell me how download file through web browser using tornado framework.

tornado comes both synchronous , asynchronous http client. can find documentation here.

here's synchronous example taken page linked above:

from tornado import httpclient http_client = httpclient.httpclient() try:     response = http_client.fetch(url)     print(response.body) except httpclient.httperror e:     print("error:", e) http_client.close() 

if want save resulting output disk instead of printing data, write out file. note in python 3, tornado returns response bodies strings:

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

of course, if response data large, you'll want download file in chunks , write disk on-the-fly (see here).

finally, if you're not constrained tornado reason, highly recommend requests library (or grequests asynchronous calls).

edit: serve static file download, in handler's 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)     open(file_name, 'r') f:         while true:             data = f.read(buf_size)             if not data:                 break             self.write(data)     self.finish() 

you may or may not have byte/string issues in python 3.


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -