【问题标题】:returning text(in variable) as a .txt file on-the-fly through http headers and etc通过 http 标头等即时将文本(在变量中)作为 .txt 文件返回
【发布时间】:2016-05-06 13:47:54
【问题描述】:

我想通过特定的路线向用户返回带有一些结果的 .txt。 所以我有:

@route('/export')
def export_results():
    #here is some data gathering ot the variable
    return #here i want to somehow return on-the-fly my variable as a .txt file

所以,我知道如何:

  • 打开、返回 static_file(root='blahroot',filename='blah')、关闭、取消链接
  • 使用“import tempfile”等进行一些类似的操作

但是:我听说我可以以某种特定方式设置响应 http 标头,将我的变量作为文本返回将由浏览器(如文件)获取。

问题是:如何让它这样运行?

P.S.:如标签所示,我在 Python3 上,使用 Bottle 并计划将来自 cherrypy 的服务器用作 wsgi 服务器

【问题讨论】:

    标签: python http python-3.x http-headers bottle


    【解决方案1】:

    如果我理解正确,您希望访问者的浏览器提供将响应保存为文件,而不是在浏览器本身中显示它。做到这一点很简单;只需设置这些标题:

    Content-Type: text/plain
    Content-Disposition: attachment; filename="yourfilename.txt"
    

    浏览器会提示用户保存文件并建议文件名“yourfilename.txt”。 (更多讨论here。)

    要在 Bottle 中设置标题,请使用 response.set_header:

    from bottle import response
    
    @route('/export')
    def export():
        the_text = <however you choose to get the text of your response>
        response.set_header('Content-Type', 'text/plain')
        response.set_header('Content-Disposition', 'attachment; filename="yourfilename.txt"')
        return the_text
    

    【讨论】:

      猜你喜欢
      • 2013-03-03
      • 1970-01-01
      • 2020-10-09
      • 2015-06-07
      • 2011-01-09
      • 2019-03-14
      • 1970-01-01
      • 2015-11-17
      • 2015-11-19
      相关资源
      最近更新 更多