【问题标题】:Google App Engine and Flask: Serving FilesGoogle App Engine 和 Flask:提供文件
【发布时间】:2013-10-26 23:15:29
【问题描述】:

我在 GAE 上运行 Flask。我在提供文件时遇到问题。一切似乎都正确,但我的浏览器中没有弹出任何提示我保存它并且日志控制台中没有错误:

@app.route("/submit", methods=["GET"])
def submitChecklist():

... generate json

headers = {'content-type': 'application/json', 'charset':'UTF-8'}
r = requests.post(url, data=json.dumps(jsonstring), headers=headers, stream=True)

print 'payload: ' + r.text
response = make_response(r.text)
response.headers["Content-Disposition"] = "attachment; filename=exportChecklists.xml"

return response

更新

我认为问题可能出在 javascript 方面,这是我目前拥有的,它没有提示下载:

$.get('submit',
        dat, 
        function(data) {
            if (data.success==1)
                console.log("done")
            else
                alert("There is an exception on server side while submitting the response!")
            },'text');

我觉得解决方案是here,但我想不通。

更新 #2

我仍然不知道如何做到这一点,所以我只提供一个文件。虽然下面的解释总的来说很好,但我不知道如何使用 jQuery 只提供 1 个文件。有人可以提供一个如何做到这一点的例子。

感谢您的帮助。

【问题讨论】:

  • 浏览器响应的标题中显示了什么?
  • 'HTTP/1.1 200 OK 内容类型:文本/html; charset=utf-8 内容配置:附件;文件名=exportChecklists.xml 缓存控制:无缓存过期:格林威治标准时间 1990 年 1 月 1 日星期五 00:00:00 内容长度:481 服务器:开发/2.0 日期:2013 年 10 月 27 日星期日 05:58:03 GMT'
  • 另外,r.text 是字符串形式的 xml,我创建的响应是否错误?
  • 我也明白了,http://localhost:8080/submit?model=123&Procedures%5B0%5D=%7B%22cIndex%22%3A%221%22%2C%22title%22%3A%22Checklist1%22%2C%22proc%22%3A%22123%22%2C%22state%22%3A%22123%22%7D 如果我在调试控制台中单击它会提示下载...但这是我能够做到的唯一方法。
  • 您必须将 window.location 设置为下载 URL。 JavaScript 无法将文件保存到您的计算机。

标签: jquery python google-app-engine flask response


【解决方案1】:

这是我为解决问题所做的,这可能不是正确的方法,但这是一个:

在 Javascript 方面:

$.get('submit',
        dat,
        function(data, status, request) {
            if (status = 'success'){
                console.log(status);
               $("body").append("<iframe src='" + request.getResponseHeader('redirect')+ "' style='display: none;' ></iframe>");
            }
            else 
                alert("There is an exception on server side while submitting the response!");

        }, 
        'xml'); 

在前端 Python 上:

  headers = {'content-type': 'application/json', 'charset':'UTF-8'}
  r = requests.post(url, data=json.dumps(jsonstring), headers=headers)
  response = make_response(r.text)
  response.headers["Content-Type"] = 'application/xml'
  response.headers.add("redirect", request.url)
  response.headers["Content-Disposition"] = 'attachment; filename="exportChecklists.xml"'

  return response

基本上,我添加了一个重定向 url,这是我的请求 url,所以当文件准备好时,我只是创建了一个隐藏的 iFrame,现代浏览器重定向到并提示下载。

如果有更好的解决方法请指正。

【讨论】:

  • 好吧,你基本上是在下载文件两次。一次是使用ajax获取头部,第二次是浏览器实际保存文件的时候。我建议使用两个单独的视图:一个返回重定向链接,另一个返回实际文件。有关 ajax 下载的更多信息,请参阅 stackoverflow.com/questions/4545311/…
  • 谢谢。两种观点是什么意思? (对不起,我对 web 开发不是很精通)
猜你喜欢
  • 1970-01-01
  • 2017-08-15
  • 2022-01-07
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 2016-09-02
相关资源
最近更新 更多