Flask Ajax错误400

时间:2018-05-03 20:20:49

标签: javascript python post flask

发布时收到错误400。我在后端使用flask和sqlalchemy,非常直接的javascript& jQuery的 这是JS:

    $.ajax({
        url: "/create",
        type: "POST",
        data: {
          question: question,
          answer1: answer1,
          answer2: answer2,
          answer3: answer3,
          answer4: answer4,
          answer5: answer5,
          answer6: answer6,
          congress: congress,
          session: session,
          date: date,
          lecture: lecture,
          correct: correct
        },
        success: function(){
            console.log("sent");
        }, error: function(xhr, textStatus, error){
            console.log(xhr.statusText);
            console.log(textStatus);
            console.log(error);
            }
    });
}

这是Flask代码:

@app.route('/create', methods=['GET', 'POST'])
def cre():
post = QuestionClass(congress=str(request.form['congress']), 
session=str(request.form['session']),
                     date=str(request.form['date']), 
lecture=str(request.form['lecture']),
                     question=str(request.form['question']), 
answer1=str(request.form['answer1']),
                     answer2=str(request.form['answer2']), answer3=str(request.form['answer3']),
                     answer4=str(request.form['answer4']), answer5=str(request.form['answer5']),
                     )

engine = create_engine(sqlite:///DB.db', echo=True)
Session = sessionmaker(bind=engine)
sqlsession = Session()
sqlsession.add(post)
sqlsession.commit()
return 1

我不能为我的生活找出错误的原因......

2 个答案:

答案 0 :(得分:0)

我也有一个彻底的外观,但找不到任何明显的东西。我做了一个小小的工作示例,它正是您希望它应该做的事情。尝试在示例中添加内容,直到打破它为止。

from flask import Flask, render_template_string, request, jsonify, url_for

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        info = request.form['question']
        print(info)
        return jsonify({'what_you_sent': info})

    return render_template_string('''
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>title</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div></div>
<script>
 $.ajax({
        url: "/",
        type: "POST",
        data: {
          question: 'hello?',
          answer1: 'hi',
         },
        success: function(data){
            alert(data.what_you_sent);},
        error: function(xhr, textStatus, error){
            alert('such error')}
    });
</script>
</body>
</html>
''')


app.run()

调试400个错误时只需要一个简单的提示,只需逐个访问表单元素,而不是直接将它们应用到模型或其他任何地方,就可以更容易地发现它们。

像:

print(request.form['question'])
print(request.form['answer1'])
etc...

另外清理浏览器缓存以防万一。

答案 1 :(得分:0)

正如我在评论中提到的,数据对象表示的是json对象,与javascript对象不同,键必须是字符串,请参阅this ref

将您的数据对象更改为(假设您的值是有效的JSON数据类型(字符串,数字,对象,数组,布尔值或空))

编辑我正在回答this question,并意识到主要问题可能是您的数据是由jquery进行网址编码的。如果你像下面那样字符串化,它应该工作。尝试使用原始代码

data: JSON.stringify({
          "question": question,
          "answer1": answer1,
          "answer2": answer2,
          "answer3": answer3,
          "answer4": answer4,
          "answer5": answer5,
          "answer6": answer6,
          "congress": congress,
          "session": session,
          "date": date,
          "lecture": lecture,
          "correct": correct
        }),

好的,我会让你的烧瓶更复杂,但是有一个很好的理由。我将制作一个wtf表单(你可以制作一个普通的表单,但我喜欢wtf的附加功能,如验证等)

class QuestionForm(FlaskForm):
    question = StringField('question', [validators.InputRequired(message="Please enter a valid entry")])
    answer1 = StringField('answer1', [validators.InputRequired(message="Please enter a valid entry")])
    answer2 = StringField('answer2', [validators.InputRequired(message="Please enter a valid entry")])
    answer3 = StringField('answer3', [validators.InputRequired(message="Please enter a valid entry")])
    answer4 = StringField('answer4', [validators.InputRequired(message="Please enter a valid entry")])
    answer5 = StringField('answer5', [validators.InputRequired(message="Please enter a valid entry")])
    answer6 = StringField('answer6', [validators.InputRequired(message="Please enter a valid entry")])
    congress = StringField('congress', [validators.InputRequired(message="Please enter a valid entry")])
    session = StringField('session', [validators.InputRequired(message="Please enter a valid entry")])
    date = StringField('date', [validators.InputRequired(message="Please enter a valid entry")])
    lecture = StringField('lecture', [validators.InputRequired(message="Please enter a valid entry")])
    correct = StringField('correct', [validators.InputRequired(message="Please enter a valid entry")])

如果使用wtf

,请务必进行relvant导入
from flask_wtf import FlaskForm
from wtforms import Form, BooleanField, StringField, IntegerField, validators, SelectField, TextAreaField, HiddenField

然后我将使用werkzeug.datastructures来访问json数据(我从导入开始,如果它在不同的文件from forms import QuestionForm中也导入表单),然后访问表单的所有值。我正在返回字符串中的所有值,以确保我收到它们,相信你会知道如何从那里保存到数据库

from werkzeug.datastructures import MultiDict
@app.route('/create', methods=['POST'])
def cre():
    form_data = MultiDict(mapping=request.json)
    form = QuestionForm(form_data)
    if request.is_json:
        question= form.question.data
        answer1= form.answer1.data
        answer2= form.answer2.data
        answer3= form.answer3.data
        answer4= form.answer4.data
        answer5= form.answer5.data
        answer6= form.answer6.data
        congress= form.congress.data
        ssession= form.session.data
        date= form.date.data
        lecture= form.lecture.data
        correct= form.correct.data
    return str(question+' '+answer1+' '+answer2+' '+answer3+' '+answer4+' '+answer5+' '+answer6+' '+congress+' '+ssession+' '+date+' '+lecture+' '+correct)

如果您希望根据在表单上指定的验证器验证数据,可以在if form.validate_on_submit():之后添加if request.is_json:

我能够得到一个包含我放在json对象中的所有值的响应。我相信如果您找到一个可以为您工作的示例,您将能够从那里进行调试(我使用了ssession,因为在我的测试应用程序中我已经定义了会话)