尝试了解当使用 JQuery AJAX POST 请求将表单数据和附加文件发送到 Flask 端点时我在这里做错了什么。
我仍在构建的基本 Flask View 如下所示:
@main.route('/videoupload', methods=['GET','POST'])
def videoupload():
if request.method == 'POST':
ajaxpost = request.form['m_data']
print(ajaxpost)
return render_template('videoupload.html')
表单和附加文件的 JQuery 如下所示:
$("#submit_btn").click(function() {
var proceed = true;
if(proceed) //everything looks good! proceed...
{
//data to be sent to server
var m_data = new FormData();
m_data.append( 'video_title', $('input[name=videoTitle]').val());
m_data.append( 'video_description', $('input[name=videoDescription]').val());
m_data.append( 'video_tags', $('input[name=videoTags]').val());
m_data.append( 'file_attach', $('input[name=file_attach]')[0].files[0]);
//instead of $.post() we are using $.ajax()
//that's because $.ajax() has more options and flexibly.
$.ajax({
url: '/videoupload',
data: m_data,
processData: false,
contentType: false,
type: 'POST',
//dataType:'json',
datatype:'json',
success: function(response){
//load json data from server and output message
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#videoform #form_results").hide().html(output).slideDown();
}
});
}
});
使用 Firebug 和 Net 窗口,我可以确认在表单字段和附加文件中输入的数据已附加到 FormData()
对象。
当用户单击“提交”按钮时,我在控制台中收到以下错误:
> POST http://127.0.0.1:8000/videoupload 400 (BAD REQUEST)
send @ jquery.js:9664
m.extend.ajax @ jquery.js:9215
(anonymous function) @ videoupload:137
n.event.dispatch @ jquery.min.js:3
r.handle @ jquery.min.js:3
Navigated to http://127.0.0.1:8000/videoupload?videoTitle=asdf&videoDescription=asdfasdfasdfasdfasdf&videoTags=ZcZXcZXcZXcZXC&file_attach=ScreenCaptureProject1.mp4
在以 Debug模式运行 Flask 应用程序(使用 Gunicorn)的终端窗口中,不会出现错误:
[2016-05-20 00:18:21 -0400] [27033] [DEBUG] POST /videoupload
POST CALLED
[2016-05-20 00:18:24 -0400] [27033] [DEBUG] GET /videoupload
看起来 AJAX 正在使用 POST 请求 ping Flask View 。我是否在 Flask View 中错误地处理了表单? Flask 不喜欢 JQuery AJAX POST 请求是否存在错误?
最佳答案
request.form
是 MultiDict与接收到的表单数据的键值对。
您正在尝试使用字符串“m_data”作为键来索引此字典,但看起来“m_data”只是 JavaScript 变量的名称,实际上并不是表单的键数据。如果 'm_data'
不是有效 key ,则会引发异常。
引用Werkzeug documentation在多字典上:
"From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions."
为了帮助调试此路由,您可以将 python 代码包装在 try- except block 中:
@main.route('/videoupload', methods=['GET','POST'])
def videoupload():
if request.method == 'POST':
try:
[your code]
except Exception, e:
print e
return render_template('videoupload.html')
然后您可以检查错误日志(如果您在本地运行 Flask 测试服务器,则在控制台中)是否出现 KeyError
。
关于javascript - 了解 AJAX Post 请求到 Flask 端点期间的 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339431/