10

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')

2 Answers 2

18

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()
0
11

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

5
  • Thank you for your answer. You say this is not to be used for big files. Any particular reason for that? Oct 9, 2012 at 6:16
  • The files I will be dealing with will be at most 50 MB in size. Oct 9, 2012 at 6:16
  • @missingfaktor: It reads the whole file in at once, which will increase memory usage substantially.
    – nneonneo
    Oct 9, 2012 at 6:31
  • @nneonneo, okay, thank you. What'll be a good alternative way? Oct 9, 2012 at 6:32
  • StaticFileHandler is certainly nice; the alternative is to just read and write chunks at a time. If you like I can add that as an answer.
    – nneonneo
    Oct 9, 2012 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.