Google App Engine和Flask:提供文件

时间:2013-10-26 23:15:30

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

我在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个文件。有人可以提供一个如何做到这一点的例子。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

以下是我为解决问题所做的工作,这可能不是正确的方法,但这里有一个:

在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

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

如果有更好的解决方案,请纠正我。