【发布时间】:2011-11-20 15:47:54
【问题描述】:
我的 Flask 路由中有一半需要一个变量,比如 /<variable>/add 或 /<variable>/remove。如何创建指向这些位置的链接?
url_for() 需要一个参数让函数路由到,但我不能添加参数?
【问题讨论】:
我的 Flask 路由中有一半需要一个变量,比如 /<variable>/add 或 /<variable>/remove。如何创建指向这些位置的链接?
url_for() 需要一个参数让函数路由到,但我不能添加参数?
【问题讨论】:
它接受变量的关键字参数:
url_for('add', variable=foo)
url_for('remove', variable=foo)
烧瓶服务器将具有以下功能:
@app.route('/<variable>/add', methods=['GET', 'POST'])
def add(variable):
@app.route('/<variable>/remove', methods=['GET', 'POST'])
def remove(variable):
【讨论】:
def add(variable)?
url_for 的kwargs 将作为函数参数传递给Flask 中的可变规则路由
@app.route("/<a>/<b>")和def function(a,b): ...作为它的函数,那么你应该使用url_for并像这样指定它的关键字参数:url_for('function', a='somevalue', b='anothervalue')
您需要添加功能意味着您要呈现该功能的页面应该添加到 url_for(function name) 中。 它将重定向到该函数,并且页面将相应地呈现。
【讨论】:
模板:
传递函数名称和参数。
<a href="{{ url_for('get_blog_post',id = blog.id)}}">{{blog.title}}</a>
视图、功能
@app.route('/blog/post/<string:id>',methods=['GET'])
def get_blog_post(id):
return id
【讨论】:
url_for 在 Flask 中用于创建 URL,以防止在整个应用程序(包括模板)中更改 URL 的开销。如果没有url_for,如果您的应用程序的根 URL 发生变化,那么您必须在链接存在的每个页面中更改它。
语法:url_for('name of the function of the route','parameters (if required)')
它可以用作:
@app.route('/index')
@app.route('/')
def index():
return 'you are in the index page'
现在如果你有一个链接索引页面:你可以使用这个:
<a href={{ url_for('index') }}>Index</a>
你可以用它做很多事情,例如:
@app.route('/questions/<int:question_id>'): #int has been used as a filter that only integer will be passed in the url otherwise it will give a 404 error
def find_question(question_id):
return ('you asked for question{0}'.format(question_id))
以上我们可以使用:
<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>
这样就可以简单的传参数了!
【讨论】:
{{ url_for('find_question' ,question_id=question.id) }} 而不是{{ url_for('find_question' ,question_id={{question.id}}) }}
参考the Flask API document for flask.url_for()
下面是用于将 js 或 css 链接到您的模板的其他示例 sn-ps。
<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
【讨论】: