通过 http headers 等将文本(在变量中)作为 .txt 文件 on-the-fly 返回

returning text(in variable) as a .txt file on-the-fly through http headers and etc

我想 return .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

所以,我知道如何:

但是:我听说我可以以某种特定方式设置响应 http headers,return 将我的变量作为文本由浏览器像文件一样获取。

问题是:如何运行这样?

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

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

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

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

要在 Bottle 中设置 headers,请使用 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