gpt4 book ai didi

python - 使用 Flask 的 URL 结构和表单帖子

转载 作者:太空狗 更新时间:2023-10-30 00:46:28 25 4
gpt4 key购买 nike

在 Flask 中,您可以像这样在方法声明上方编写路由:

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

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

www.myapp.com/search?location=paris

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

www.myapp.com/search/london

将按预期返回。

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

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

最佳答案

查询参数不包含在路由匹配中,也不会注入(inject)到函数参数中。仅注入(inject)匹配的 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)

等等。

关于python - 使用 Flask 的 URL 结构和表单帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8735603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com