我想通过特定路线向用户返回.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标头,将文件作为文本返回将由浏览器获取,如文件。
问题是:如何让它以这种方式运行?
P.S。:如标签所示我在Python3上,使用Bottle并计划将cherrypy服务器作为wsgi服务器
答案 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