[英]How to use kwargs in Flask's url_for method
I have a certain method methodA
that I need to add optional arguments to in Flask. 我有一定的方法methodA
,我需要在Flask中添加可选参数。 This is typically trivial with the use of **kwargs
-- 使用**kwargs
通常很简单-
@subapp.route('endpoint',methods=['GET','POST'])
def methodA(required_arg,**kwargs):
#stuff
But my problem arises when I try and invoke **kwargs
using url_for()
in the template. 但是,当我尝试在模板中使用url_for()
调用**kwargs
时,就会出现我的问题。 In django
, something like this would work just fine -- 在django
,类似这样的方法就可以正常工作-
<a href = "{{url_for('subapp.methodA',required_arg='arg',kwargs={'additional_arg':'arg'})}}">A Link</a>
When I try that in Flask, it simply interprets the kwargs={'additional_arg':'arg'}
as raw text and escapes everything, ignoring the variable in the process. 当我在Flask中进行尝试时,它只是将kwargs={'additional_arg':'arg'}
为原始文本并转义所有内容,而忽略了该过程中的变量。 This same exact question was asked earlier . 之前也问过同样的问题。 However, omitting the kwargs=
part as the OP did, something like 但是,像OP一样,省略了kwargs=
部分,类似
<a href = "{{url_for('subapp.methodA',required_arg='arg', {'additional_arg':'arg'})}}">A Link</a>
gives me a TemplateSyntaxError
, specifically 给我一个TemplateSyntaxError
,特别是
TemplateSyntaxError: invalid syntax for function call expression
Additionally, the older question's accepted answer doesn't explain how to properly add the additional arguments in url_for
. 此外,旧问题的可接受答案没有说明如何在url_for
正确添加其他参数。 Consequently, request.args
fails to capture the arguments in kwargs
. 因此, request.args
无法捕获kwargs
的参数。 Even if kwargs=
remains in url_for
, request.args
still fails to extract the extra arguments. 即使kwargs=
保留在url_for
, request.args
仍然无法提取额外的参数。 (To be precise, Flask doesn't even make it to the method -- it escapes kwargs
entirely and yields a 404
error) The older question didn't have anything useful for my problem -- does anyone have any new advice as to what I should do? (确切地说,Flask甚至没有采用该方法-它完全逃避了kwargs
并产生404
错误)。较早的问题对我的问题没有任何帮助-任何人都对什么有任何新建议我应该做?
以与Python中相同的方式传递额外的参数,如key='value'
:
<a href = "{{url_for('subapp.methodA', required_arg='arg', additional_arg='arg')}}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.