我是 flask 新手。我试图将发布/重定向/获取模式应用于我的程序。这就是我所做的。
在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 .
。句点 (.
) 表示“当前目录”。所以发生的事情是您单击“提交”,然后您的浏览器 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 会处理它。
您没有发布 search.html
的代码,但也尝试将上面相同的逻辑应用于该模板;希望这能解决问题!
关于python - 如何检测 POST 请求(flask)上的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947177/