如何检测 POST 请求(烧瓶)上的错误?

How to detect bugs on POST request(flask)?

我是 Flask 的新手。我试图将 post/redirect/get 模式应用于我的程序。这是我所做的。

在index.html

{% block page_content %}
<div class="container">
    <div class="page-header">
        <h1>Hello, {% if user %} {{ user }} {% else %} John Doe {% endif %}: {% if age %} {{ age }} {% else %} ?? {% endif %}</h1>
    </div>
</div>
    {% if form %}
    {{wtf.quick_form(form)}}
    {% endif %}
{% endblock %}

在views.py

class NameForm(Form):
    age = DecimalField('What\'s your age?', validators=[Required()])
    submit = SubmitField('Submit')

''''''
@app.route('/user/<user>', methods=['GET', 'POST'])
def react(user):
    session['user'] = user
    form = NameForm()
    if form.validate_on_submit():
        old_age = session.get('age')
        if old_age != None and old_age != form.age.data:
            flash('age changed')
            session['age'] = form.age.data
        return redirect(url_for('react', user = user))
    return render_template('index.html', user = user, age = session.get('age'), form = form, current_time = datetime.utcnow())

当我打开 xxxx:5000/user/abc 时,GET 请求得到了很好的处理。但是,POST 请求失败。我收到 404 错误。我认为 url_for 函数可能会给 redirect 一个错误的值。如何检查 url_for?

返回的值

我尝试使用数据库时出现 405 错误。这回没头绪了

@app.route('/search', methods=['GET', 'POST'])
def search():
    form = SearchForm() # a StringField to get 'name' and SubmitField
    if form.validate_on_submit():
        person = Person.query.filter_by(name = form.name.data) # Person table has two attributes 'name' and 'age'
        if person is None:
            flash('name not found in database')
        else:
            session['age'] = person.age
            return redirect(url_for('search'))
    return render_template('search.html', form = form, age = session.get('age'), current_time = datetime.utcnow())

当POST请求失败时,有没有方便的调试方法?

问题不在于 url_for(),而是您使用 wtf.quick_form() 的方式。看看你的代码生成的表单:

<form action="." method="post" class="form" role="form">

action="." 行告诉浏览器获取给定的信息,POST 将其发送到 URL .。句点 (.) 表示 "current directory." 所以发生的事情是您单击提交,然后您的浏览器 POST 发送到 localhost:5000/users/。 Flask 看到这个对 /users/ 的请求并且无法提供它,因为 /users/ 不是有效的 URL。这就是您收到 404 的原因。

幸运的是,这可以修复。在 index.html 中,尝试调用 quick_form() 并传入一个操作:

{{wtf.quick_form(form, action=url_for('react', user=user))}}

现在,您的表单呈现如下:

<form action="/user/abc" method="post" class="form" role="form">

并且您的浏览器知道 POST 到 /user/abc 的表单,这是一个有效的 URL,所以 Flask 会处理它。

您没有 post search.html 的代码,但也尝试将上述相同的逻辑应用于该模板;希望这会解决问题![​​=25=]