In a certain GET
request, I need to read a file locally, depending on parameters in the request, and send it on request's input stream. How do I do it?
class GetArchives(tornado.web.RequestHandler):
def get(self, param1, param2):
path = calculate_path(param1, param2)
try:
f = open(path, 'rb')
# TODO: send this file to request's input stream.
except IOError:
raise tornado.web.HTTPError(404, 'Invalid archive')
Here's a solution that works for arbitrary-sized files:
with open(path, 'rb') as f:
while 1:
data = f.read(16384) # or some other nice-sized chunk
if not data: break
self.write(data)
self.finish()
Try this(not for big file):
try:
with open(path, 'rb') as f:
data = f.read()
self.write(data)
self.finish()
There is StaticFileHandler
in tornado, see tornado doc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With