6

在 Flask 中,您在方法声明上方编写路由,如下所示:

@app.route('/search/<location>/')
def search():
  return render_template('search.html')

但是在 HTML 中,表单将以这种方式发布到 url:

www.myapp.com/search?location=paris

后者似乎从应用程序返回 404

www.myapp.com/search/london

将按预期返回。

我确信有一个简单的难题我没有得到,但路由引擎肯定会考虑查询字符串参数以满足规则要求。

如果不是,那么这种情况的最佳解决方案是什么,因为我确信 90% 的开发人员必须达到这一点。

4

1 回答 1

10

查询参数不包含在路由匹配中,也不注入函数参数。仅注入匹配的 URL 部分。您正在寻找的是request.args(GET 查询参数)、request.form(POST)或request.values(组合)。

如果你想同时支持两者,你可以这样做:

@app.route('/search/<location>')
def search(location=None):
    location = location or request.args.get('location')
    # perform search

虽然,假设您可能想要搜索其他参数,但最好的方法可能更接近:

def _search(location=None,other_param=None):
    # perform search

@app.route('/search')
def search_custom():
    location = request.args.get('location')
    # ... get other params too ...
    return _search(location=location, other params ... )

@app.route('/search/<location>')
def search_location(location):
    return _search(location=location)

等等。

于 2012-01-05T04:42:02.673 回答