flask url功能不正常

时间:2018-04-10 01:12:32

标签: python python-3.x flask

我有一个用POST发送数据的html表单然后我使用GET重定向到同一个函数,表单数据作为函数的参数

@app.route('/search/custom/', methods=['GET', 'POST'])
def search_custom(category=None, date=None, page=None):

    if request.method == 'POST':
        category = request.form.get('InputCategory')
        date = request.form.get('InputDate')
        return redirect(url_for('search_custom', category=category, date=date, page=1))

    if request.method == 'GET':
        if not(category and date and page):
            return redirect(url_for('home'))

        flash('worked', 'success')
        return redirect(url_for('register'))

函数正确接收参数但它只重定向到“home”:

127.0.0.1 - - [10/Apr/2018 01:55:36] "GET /search/custom/?category=Vetements&date=Dernier+mois&page=1 HTTP/1.1" 302 -

1 个答案:

答案 0 :(得分:1)

处理get请求时,

类别,日期和页面都是None。

在Get处理程序内部,您需要实际从查询字符串中提取参数。

类似的东西:

category = request.args.get('category')
date = request.args.get('date')
page = request.args.get('page')

应该这样做。

在检查参数之前,它应该有效。

我没有机会对此进行测试,所以让我知道它是否不起作用我真的会深入研究它。

现在你的方式,你可能想要一个格式化的网址。像/search/custom/<category>/<date>/<page>这样的东西。这也需要更改传入URL的格式,这可能不是你想要的。

代码看起来像

@app.route('/search/custom/<category>/<date>/<page>', methods=['GET', 'POST'])
@app.route('/search/custom/', methods=['GET', 'POST'])
def search_custom(category=None, date=None, page=None):
    # do stuff