在 Flask 应用程序中提交表单时出现错误请求错误的原因是什么? [英] What is the cause of the Bad Request Error when submitting form in Flask application?

查看:29
本文介绍了在 Flask 应用程序中提交表单时出现错误请求错误的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了许多类似的问题和相关的 Flask 文档后,我似乎无法弄清楚提交表单时是什么导致了以下错误:

After reading many similar sounding problems and the relevant Flask docs, I cannot seem to figure out what is generating the following error upon submitting a form:

400 错误请求

浏览器(或代理)发送了一个该服务器无法理解的请求.

The browser (or proxy) sent a request that this server could not understand.

虽然表单总是正确显示,但当我提交与以下任一功能相关的 HTML 表单时,就会发生错误请求:

While the form always displays properly, the bad request happens when I submit an HTML form that ties to either of these functions:

@app.route('/app/business', methods=['GET', 'POST'])
def apply_business():
    if request.method == 'POST':    
        new_account = Business(name=request.form['name_field'], email=request.form['email_field'], account_type="business", 
            q1=request.form['q1_field'], q2=request.form['q2_field'], q3=request.form['q3_field'], q4=request.form['q4_field'], 
            q5=request.form['q5_field'], q6=request.form['q6_field'], q7=request.form['q7_field'],
            account_status="pending", time=datetime.datetime.utcnow())
        db.session.add(new_account)
        db.session.commit()
        session['name'] = request.form['name_field']    
        return redirect(url_for('success'))
    return render_template('application.html', accounttype="business")          

@app.route('/app/student', methods=['GET', 'POST'])
def apply_student():    
    if request.method == 'POST':    
        new_account = Student(name=request.form['name_field'], email=request.form['email_field'], account_type="student", 
            q1=request.form['q1_field'], q2=request.form['q2_field'], q3=request.form['q3_field'], q4=request.form['q4_field'], 
            q5=request.form['q5_field'], q6=request.form['q6_field'], q7=request.form['q7_field'], q8=request.form['q8_field'], 
            q9=request.form['q9_field'], q10=request.form['q10_field'],
            account_status="pending", time=datetime.datetime.utcnow())
        db.session.add(new_account)
        db.session.commit()
        session['name'] = request.form['name_field']    
        return redirect(url_for('success')) 
    return render_template('application.html', accounttype="student")

HTML 的相关部分是

The relevant part of HTML is

<html>
<head>
    <title>apply</title>
</head>
<body>
    {% if accounttype=="business" %}
    <form action="{{ url_for('apply_business') }}" method=post class="application_form">
    {% elif accounttype=="student" %}
    <form action="{{ url_for('apply_student') }}" method=post class="application_form">     
    {% endif %} 
    <p>Full Name:</p>
    <input name="name_field" placeholder="First and Last">
    <p>Email Address:</p>
    <input name="email_field" placeholder="your@email.com">
    ...

大多数人的问题不是调用 GETPOST,但我在这两个函数中都这样做,我仔细检查以确保我导入了所有必要的东西,例如from flask import request.我还查询了数据库,确认没有添加表单中的添加项.

The problem for most people was not calling GET or POST, but I am doing just that in both functions, and I double checked to make sure I imported everything necessary, such as from flask import request. I also queried the database and confirmed that the additions from the form weren't added.

在 Flask 应用程序中,我请求在 HTML 表单中标记略有不同的表单字段.保持名称一致是必须的.可以在这个问题中阅读更多内容表单发送错误,烧瓶

In the Flask app, I was requesting form fields that were labeled slightly different in the HTML form. Keeping the names consistent is a must. More can be read at this question Form sending error, Flask

推荐答案

解决方案很简单,在评论中也没有透露.如本问题所述,表单发送错误,Flask,并由 肖恩·维埃拉

The solution was simple and uncovered in the comments. As addressed in this question, Form sending error, Flask, and pointed out by Sean Vieira,

...问题是 Flask 在找不到输入参数并形成字典.Flask 默认假设的内容是如果你要一个特定的钥匙,但它不存在,那么请求中遗漏了一些东西,整个请求是无效.

...the issue is that Flask raises an HTTP error when it fails to find a key in the args and form dictionaries. What Flask assumes by default is that if you are asking for a particular key and it's not there then something got left out of the request and the entire request is invalid.

换句话说,如果只有一个您在 Python 中请求的表单元素在 HTML 中找不到,则 POST 请求无效并出现错误,在我的情况下,回溯中没有任何违规行为.对我来说,这是拼写不一致:在 HTML 中,我标记了各种表单输入

In other words, if only one form element that you request in Python cannot be found in HTML, then the POST request is not valid and the error appears, in my case without any irregularities in the traceback. For me, it was a lack of consistency with spelling: in the HTML, I labeled various form inputs

<input name="question1_field" placeholder="question one">

在 Python 中,当有一个 POST 调用时,我用

while in Python, when there was a POST called, I grab a nonexistent form with

request.form['question1']

然而,为了与我的 HTML 表单名称保持一致,它需要是

whereas, to be consistent with my HTML form names, it needed to be

request.form['question1_field']

我希望这会有所帮助.

这篇关于在 Flask 应用程序中提交表单时出现错误请求错误的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆