Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a binary file in Tornado

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')
like image 590
missingfaktor Avatar asked Oct 09 '12 06:10

missingfaktor


2 Answers

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()
like image 145
nneonneo Avatar answered Oct 09 '22 13:10

nneonneo


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

like image 41
iMom0 Avatar answered Oct 09 '22 14:10

iMom0