Jay*_*Jay 5 python routing werkzeug flask
在Flask中,您可以在方法声明之上编写路由,如下所示:
@app.route('/search/<location>/')
def search():
return render_template('search.html')
Run Code Online (Sandbox Code Playgroud)
但是在HTML中,表单将以这种方式发布到url
www.myapp.com/search?location=paris
Run Code Online (Sandbox Code Playgroud)
后者似乎从应用程序中返回404
www.myapp.com/search/london
Run Code Online (Sandbox Code Playgroud)
将按预期返回.
我确信我没有得到一个简单的谜题,但路由引擎肯定会考虑查询字符串参数以满足规则要求.
如果不是这种情况的最佳解决方案是什么,因为我确信90%的开发人员必须到达这一点......
提前致谢.
查询参数不包含在路由匹配中,也不会注入函数参数.仅注入匹配的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
Run Code Online (Sandbox Code Playgroud)
虽然,假设您可能想要搜索其他参数,可能最好的方法是更接近:
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)
Run Code Online (Sandbox Code Playgroud)
等等.