Forums

Flask Refresh page after return response

Flask code

How can I accomplish that the page is refreshed after response is returned?

I'm not sure what do you expect.

The web site should be refreshed after 'return response' (after file is downloaded).

Right now you're returning a response as an attachment, which tells the browser to download the file using its download mechanism without refreshing the page. If you add a new header:

Refresh: 0; url=http://www.something.com/

...then it will also move to the specified page at the same time, so perhaps you can do that (replacing the URL with your site's)?

I tried it with this code:

@app.route("/", methods=["GET", "POST"])
def my_page():
    if request.method == "POST":
        f = request.files.get("file")
        if f:
            filename = secure_filename(f.filename)
            file_path = os.path.join('temp_files', filename)
            f.save(file_path)
            output_data = get_numbers(file_path)
            response = make_response(output_data)
            response.headers["Content-Disposition"] = \
                f"attachment; filename={filename[:-4]}.txt"
            response.headers["Refresh"] = \
                "0; url=https://jw30.pythonanywhere.com"
            os.remove(file_path)

            return response

    return render_template('index.html')

but it doesn't work unfortunately.

I'm not sure that a refresh from a file download makes any sense from the browser's point of view. My guess would be that browsers would just ignore that header on downloads. I think it's unlikely that you'd be able to do what you're trying to do.

Is it not possible to download a file and redirect after?

It might be possible, but I think it's unlikely.