通过http标头等动态地将文本(在变量中)作为.txt文件返回

时间:2016-05-06 13:47:55

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

我想通过特定路线向用户返回.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服务器

1 个答案:

答案 0 :(得分:0)

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

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