Python 带有多个参数的 Flask url_for()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17873820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask url_for() with multiple parameters
提问by agconti
The Problem:
问题:
I have an a input button in a form that when its submitted should redirect two parameters , search_val
and i
, to a more_results()
function, (listed below), but I get a type error when wsgi builds.
我有一个表单中的输入按钮,当它提交时应该将两个参数 ,search_val
和i
,重定向到一个more_results()
函数(如下所列),但是在构建 wsgi 时出现类型错误。
The error is: TypeError: more_results() takes exactly 2 arguments (1 given)
错误是: TypeError: more_results() takes exactly 2 arguments (1 given)
html:
html:
<form action="{{ url_for('more_results', past_val=search_val, ind=i ) }}" method=post>
<input id='next_hutch' type=submit value="Get the next Hunch!" name='action'>
</form>
flask function:
烧瓶功能:
@app.route('/results/more_<past_val>_hunches', methods=['POST'])
def more_results(past_val, ind):
if request.form["action"] == "Get the next Hunch!":
ind += 1
queried_resturants = hf.find_lunch(past_val) #method to generate a list
queried_resturants = queried_resturants[ind]
return render_template(
'show_entries.html',
queried_resturants=queried_resturants,
search_val=past_val,
i=ind
)
Any idea on how to get past the build error?
关于如何克服构建错误的任何想法?
What I've tried:
我试过的:
Creating link to an url of Flask app in jinja2 template
在 jinja2 模板中创建指向 Flask 应用程序 url 的链接
for using multiple paramters with url_for()
用于在 url_for() 中使用多个参数
Build error with variables and url_for in Flask
similar build erros
类似的构建错误
As side note, the purpose of the function is to iterate through a list when someone hits a "next page" button. I'm passing the variable i
so I can have a reference to keep incrementing through the list. Is there a flask / jinja 2 method that would work better? I've looked into the cycling_list feature but it doesn't seem to able to be used to render a page and then re-render it with cycling_list.next()
.
作为旁注,该函数的目的是在有人点击“下一页”按钮时遍历列表。我正在传递变量,i
所以我可以有一个引用来在列表中不断增加。有没有更好的烧瓶/jinja 2 方法?我已经研究了cycling_list 功能,但它似乎无法用于渲染页面,然后使用cycling_list.next()
.
采纳答案by Amber
Your route doesn't specify how to fill in more than just the one past_val
arg. Flask can't magically create a URL that will pass two arguments if you don't give it a two-argument pattern.
您的路线没有指定如何填写不仅仅是一个past_val
参数。如果你不给它一个双参数模式,Flask 不能神奇地创建一个将传递两个参数的 URL。
回答by plaes
It's also possible to create routes that support variable number of arguments, by specifying default values to some of the arguments:
通过为某些参数指定默认值,还可以创建支持可变数量参数的路由:
@app.route('/foo/<int:a>')
@app.route('/foo/<int:a>/<int:b>')
@app.route('/foo/<int:a>/<int:b>/<int:c>')
def test(a, b=None, c=None):
pass