简体   繁体   中英

Flask: request.method =='POST' skips return statement

I have a strange problem with my app.

What I am doing is: I generate a csv file in JS(client side) and then send it to flask where I then filter the file using python script and then return it back to the client.

Everything works great except the last part. When it comes to return render_template it just skips that part. Which is strange since it goes inside of the if request.method == 'POST' . I printed the values inside of the if request.method=='POST' and I can see the values on the server side.

Flask routes.py:

@app.route('/update_file', methods=['GET', 'POST'])
@login_required
def update_file():
    '''Opens the filtered_file page but with updated file'''
    clicked = None
    if request.method == 'POST':
        clicked = io.StringIO(request.form['data'])
        file_to_filter = pd.read_csv(clicked, sep=',', engine='python', encoding='utf_8_sig')
        table1 = update_csv(file_to_filter)
        print(table1)
        table2 = table1.to_html(classes='my_class" id = "my_id')
        return render_template('3_filtered_file.html', data=table2)

This is how I show it on my html template:

 <div class="table-responsive">
    {{data | safe}}
</div>

I already did similar with the client uploaded file and it works great but this one has an error that I can't seem to find:/

EDIT: This the JS where I send the ajax rquest:

//On Update click renders table to csv, activates the be_filter and reopens it in the filtered_file.html
var isClicked;
jQuery("#update").on('click', function(){
    var response = confirm('Are you sure you want to UPDATE rows ?');
    if(response == true){                    
        isClicked = $('#my_id').table2csv();
        $.ajax({
            type:'POST',
            url:"{{url_for('update_file')}}",
            data: {'data': isClicked}
        });
         //window.location.href='/update_file';
    }else{
        return false;
    }
});

The problem here is you're using AJAX when you should be submitting a form instead. AJAX is primarily about communicating with the server in the background , but you're trying to use it as a tool for submitting POST form data programmatically. Using AJAX will send a request to the server just like clicking a link or submitting a form would, but the browser does not navigate to the result . This is why you concluded that flask skips the render_template call, but the template does indeed get rendered. It's just that with an AJAX call, the reply only ends up in the AJAX success callback, not in the browser's main window.

In the case of an AJAX request like this, there's no need to send back HTML. You could for instance simply return "update successful" .

You can fix your existing code by redirecting to the result page manually from the client:

// in your $.ajax() options:
success: function(reply) {
  if (reply == "update successful") location = "/table"; // URL of table view
  else alert("server reports error");
}

This will redirect on the client after the AJAX call has successfully updated the CSV file on the server.

However you can simply submit an actual form instead:

<form id="tableDataForm" method="post" action="{{url_for('update_file')}}">
  <input type="hidden" name="data" id="tableData">
</form>
$("#update").on('click', function(){
    $('#tableData').val($('#my_id').table2csv()); // insert data into hidden <input>
    $('#tableDataForm').submit();  // send POST request
});

This is all you need. Now the browser will once again display the reply sent back by flask.

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