【问题标题】:Using StaticFileHandler to host a file on Tornado Python使用 StaticFileHandler 在 Tornado Python 上托管文件
【发布时间】:2013-07-18 13:36:39
【问题描述】:

您好,我正在尝试在 Tornado 中使用 StaticFileHandler,并且大部分情况下它都在工作,除了当我单击下载时它在网页中输出文件 (.csv)。我可以保存文件的唯一方法是右键单击并将目标另存为(但这不适用于所有浏览器)。

如何强制下载文件? 我知道我需要像这样设置 StaticFileHandler 的标题:

    self.set_header('Content-Type','text-csv')
    self.set_header('Content-Disposition','attachment')

但我不知道如何设置它,因为它是默认处理程序。

感谢您的宝贵时间!

【问题讨论】:

    标签: python file static tornado


    【解决方案1】:

    扩展 web.StaticFileHandler

    class StaticFileHandler(web.StaticFileHandler):
        def get(self, path, include_body=True):
            if [some csv check]:
                # your code from above, or anything else custom you want to do
                self.set_header('Content-Type','text-csv')  
                self.set_header('Content-Disposition','attachment')
    
            super(StaticFileHandler, self).get(path, include_body)
    

    不要忘记在处理程序中使用您的扩展类!

    【讨论】:

    • 请注意,这可能有效,但 web.StaticFileHandler 的文档明确不鼓励覆盖 get 方法。支持类方法“set_extra_headers(path)”,可以改为使用。
    【解决方案2】:

    由于 cmets 容易被删除,正确的解决方案(如Jan 的评论中所述)是:

    [T]web.StaticFileHandler 的文档明确不鼓励覆盖 get 方法。类方法 'set_extra_headers(path)' 受支持,可以替代使用。

    正确的解决方案如下所示:

    class StaticFileHandler(web.StaticFileHandler):
        @classmethod
        def set_extra_headers(self, path):
            if path.endswith('.csv'):
                self.set_header('Content-Type', 'text-csv')  
                self.set_header('Content-Disposition', 'attachment')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-07
      • 2013-07-13
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多