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

时间:2015-06-19 20:58:36

标签: python flask flask-wtforms

我是烧瓶的新手。我试图将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请求失败时是否有方便的调试方法?

1 个答案:

答案 0 :(得分:1)

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

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

action="."行告诉浏览器获取给定的信息并将其发布到网址.。句点(.)表示&#34;当前目录。&#34;所以,您正在点击提交,然后您的浏览器发布到localhost:5000/users/。 Flask将此请求发送给/users/并且无法提供,因为/users/不是有效的网址。这就是你获得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">

并且您的浏览器知道将表单发布到/user/abc,这是一个有效的网址,因此Flask会处理它。

您没有发布search.html的代码,但也尝试将相同的逻辑应用于该模板;希望能解决这个问题!