烧瓶:request.method =='POST'跳过return语句

我的应用有一个奇怪的问题。

我正在做的是: 我在JS(客户端)中生成一个csv文件,然后将其发送到flask,然后在其中使用python脚本过滤该文件,然后将其返回给客户端。

除最后一部分外,其他所有功能都非常有效。当涉及到返回render_template 时,它只是跳过了这一部分。这很奇怪,因为它位于 if request.method =='POST'内部。我在 if request.method =='POST'中打印了这些值,然后可以在服务器端看到这些值。

烧瓶路线.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)

这就是我在html模板上显示它的方式:

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

我已经对客户端上载的文件进行了类似的操作,效果很好,但是这个错误有一个我似乎找不到的错误:/

编辑: 这是我发送ajax rquest的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;
    }
});
liteiken 回答:烧瓶:request.method =='POST'跳过return语句

这里的问题是您应该使用AJAX来提交表单。 AJAX主要是关于与服务器在后台进行通信,但是您正在尝试将其用作以编程方式提交POST表单数据的工具。使用AJAX会将请求发送到服务器,就像单击链接或提交表单一样,但是浏览器不会导航到结果。这就是为什么您得出结论,flask跳过了render_template调用,但是确实确实渲染了模板的原因。只是通过AJAX调用,答复只会在AJAX成功回调中结束,而不会在浏览器的主窗口中结束。

对于这样的AJAX请求,不需要发送回HTML。例如,您可以简单地返回"update successful"

您可以通过从客户端手动重定向到结果页面来修复现有代码:

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

这将在AJAX调用成功更新服务器上的CSV文件后在客户端上重定向。

不过,您可以直接提交实际的表格:

<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
});

这就是您所需要的。现在,浏览器将再次显示烧瓶返回的回复。

本文链接:https://www.f2er.com/3124170.html

大家都在问