简体   繁体   English

Flask:request.method =='POST' 跳过返回语句

[英]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.我正在做的是:我在 JS(客户端)中生成一个 csv 文件,然后将其发送到 flask,然后我使用 python 脚本过滤文件,然后将其返回给客户端。

Everything works great except the last part.除了最后一部分,一切都很好。 When it comes to return render_template it just skips that part.当涉及到返回 render_template时,它只是跳过了那部分。 Which is strange since it goes inside of the if request.method == 'POST' .这很奇怪,因为它进入了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.我在if request.method=='POST'中打印了值,我可以在服务器端看到这些值。

Flask routes.py: 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:这就是我在 html 模板上显示它的方式:

 <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:编辑:这是我发送 ajax 请求的 JS:

//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。 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. AJAX 主要是关于在后台与服务器通信,但您正试图将其用作以编程方式提交 POST 表单数据的工具。 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 .使用 AJAX 将向服务器发送请求,就像单击链接或提交表单一样,但浏览器不会导航到结果 This is why you concluded that flask skips the render_template call, but the template does indeed get rendered.这就是为什么您得出结论认为 flask 跳过了render_template调用,但模板确实被渲染了。 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.只是通过 AJAX 调用,回复只会在 AJAX 成功回调中结束,而不是在浏览器的主 window 中。

In the case of an AJAX request like this, there's no need to send back HTML.在像这样的 AJAX 请求的情况下,不需要发回 HTML。 You could for instance simply return "update successful" .例如,您可以简单地返回"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.在 AJAX 调用成功更新服务器上的 CSV 文件后,这将在客户端上重定向。

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.现在浏览器将再次显示 flask 发回的回复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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