9

在某个GET请求中,我需要根据请求中的参数在本地读取文件,并将其发送到请求的输入流中。我该怎么做?

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

2 回答 2

16

这是适用于任意大小文件的解决方案:

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()
于 2012-10-09T06:56:10.553 回答
10

试试这个(不适用于大文件):

try:
    with open(path, 'rb') as f:
        data = f.read()
        self.write(data)
    self.finish()

龙卷风中有StaticFileHandler,请参阅龙卷风文档

于 2012-10-09T06:11:23.667 回答