在Tornad中发送二进制文件

2024-04-19 19:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

在某个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')

Tags: 文件pathselfweb参数getdeftornado
2条回答

以下是一个适用于任意大小文件的解决方案:

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:
    with open(path, 'rb') as f:
        data = f.read()
        self.write(data)
    self.finish()

龙卷风中有StaticFileHandler,见tornado doc

相关问题 更多 >