2

我正在使用 Flask 和 Flask-WTF,我的views.py文件中有以下代码:

from flask import render_template, flash, redirect, url_for   
from . import app, forms

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = forms.HelpSearch()
    if form.validate_on_submit():
        flash('Searched for: %s' % form.value.data)
        redirect(url_for('help', form.value.data))
    return render_template('index.html', title='Index', form=form)


@app.route('/help/<keyword>', methods=['GET', 'POST'])
def help(keyword=None):
    form = forms.HelpSearch()
    if form.validate_on_submit():
        flash('Searched for: %s' % form.value.data)
        redirect(url_for('help', keyword=form.value.data))

    # This is just some dummy data for testing my template
    keywords = ['n', 'north']
    groups = ['movement']
    syntax = [
        {'cmd':"n", 'args': ''},
        {'cmd':'north', 'args': ''}
    ]
    content = 'Move north'

    return render_template('show_help.html',
                            title=keyword,
                            form=form,
                            keywords=keywords,
                            groups=groups,
                            syntax=syntax,
                            content=content)

我想要并期望它做的是,当有人在表单搜索字段中放置一些文本并点击搜索按钮时,它会返回该值,然后我重定向到适当的页面,例如他们搜索foo并最终到达 /help /富。

遗憾的是,来自表单验证位的重定向没有按需要重定向。它似乎正在重新加载当前页面。

我知道表单正在获取并返回数据,因为flash调用显示了正确的信息,例如,'Searched for: foo'但是当我将关键字传递给url_for页面时,再次简单地重新加载。手动导航到/help/foo工作正常。

我已经测试过它url_for正在工作,当我手动输入关键字时,它会根据需要创建适当的路径,例如print url_for('help', keyword='foo')prints /help/foo

任何人都知道为什么它没有按需要重定向?

编辑:如果有人想看看到底发生了什么,让它在Heroku上运行。

4

2 回答 2

0

我认为你的问题是不返回任何东西

你可以检查这个:

def index():
    form = forms.HelpSearch()
    if form.validate_on_submit():
        flash('Searched for: %s' % form.value.data)
        return redirect(url_for('help', keyword=form.value.data))
    return render_template('index.html', title='Index', form=form)
于 2014-10-18T14:42:46.340 回答
0

问题在于您如何进行重定向。而不是这个:

redirect(url_for('help', keyword=form.value.data))

做这个:

return redirect(url_for('help', keyword=form.value.data))

redirect()函数不会引发异常abort(),它只是返回一个Response需要向上传递堆栈的对象。

于 2014-10-18T19:30:48.890 回答