Lucifer N.
Lucifer N.

Reputation: 1056

Flask - not responding to a GET request properly?

I am trying to have a download button on a page that will start a download of a file when it is clicked. Using flask as my framework. I'm trying to start the download when the button is clicked and sends a GET request, but nothing is happening. In my console I am just getting "127.0.0.1 - - [04/Feb/2014 00:10:57] "GET /CpFTHHpsJ/ HTTP/1.1" 200 -", which is the same output I get when the page is loaded.

My HTML form looks like:

<form method="get" action="">
<input type="submit" value="DOWNLOAD">
</form>

My python for rendering the download page and sending the file:

@app.route('/<new_folder_name>/', subdomain='f', methods=['GET'])
def uploaded_file(new_folder_name):
    new_folder_path = os.path.join(app.config['FILE_FOLDER'], new_folder_name)
    filename = subfolder_fetch(new_folder_path)
    return render_template("download.html", filename=filename, new_folder_path=new_folder_path)
    if request.method == "GET":
        send_from_directory(new_folder_path, filename, as_attachment=True)

Sorry if this is stupid, I'm a beginner with both HTML forms and web programming. Thank you.

Upvotes: 1

Views: 204

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159855

  1. You never actually return your send_from_directory, so the file will never be returned to the end user.
  2. You will never get to the code, regardless, because you return render_template before you get to your test method.
  3. There is no way for you to distinguish a page load from a "Download" click with the code you have there.

How to fix #3

  • Add a name to the Download link form:

    <input type="submit" name="action" value="Download">
    

    and test for its existence in your controller:

    if "action" in request.args:
        # Download
    else:
        # Show page
    
  • Alternately, use a link pointing at a separate controller:

    @app.route('/<folder>/download')
    def download_file(folder):
        # etc.
    

    and in your template create a link and style it like a button:

    <a href="{{ url_for('download_file', folder=folder) }}" class="download">Download Now</a>
    

Upvotes: 2

Related Questions