简体   繁体   中英

Google App Engine and Flask: Serving Files

I am running Flask on GAE. I have an issue serving up my file. Everything seems right but nothing pops up in my browser to prompt me to save it and there are no errors in the log console:

@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

UPDATE

I am thinking the problem might be on the javascript side, here is what I currently have and it does not prompt download:

$.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');

I feel like the solution is here but I can't quite figure it out.

UPDATE #2

I still can't figure out how to do this so I only serve one file. While the below explanation is good in general, I can't figure out how to serve only 1 file using jQuery. Could someone please provide an example on how to do this.

Thanks for the help.

Here is what I did to solve the problem, this may not be the proper way but here is one:

On the Javascript side:

$.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'); 

On the frontend 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

Basically, I added a redirect url which was my request url to start with, so when the file was ready, I just created an hidden iFrame that modern browsers redirect to and prompt for download.

Please correct me if there is a better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM