首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以.txt文件的形式返回文本(以变量表示),通过http报头等等。

以.txt文件的形式返回文本(以变量表示),通过http报头等等。
EN

Stack Overflow用户
提问于 2016-05-06 13:47:54
回答 1查看 1.3K关注 0票数 2

我想通过特定的路由将一些结果返回给用户。所以我有:

代码语言:javascript
复制
@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'),关闭,取消链接
  • 使用“导入tempfile”等做一些类似的操作

但是:我听说我可以以某种特定的方式设置响应http头,将我的变量作为文本返回给浏览器,就像文件一样。

问题是:如何使它以这种方式运行?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-06 18:20:32

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

代码语言:javascript
复制
Content-Type: text/plain
Content-Disposition: attachment; filename="yourfilename.txt"

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

若要设置瓶中的标头,请使用response.set_header

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37074068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档