我的Flask路线的一半需要变量说,/<variable>/add
或/<variable>/remove
.如何创建指向这些位置的链接?
url_for()
为函数路由到一个参数,但我不能添加参数?
Fog*_*ird 238
它接受变量的关键字参数:
url_for('add', variable=foo)
Run Code Online (Sandbox Code Playgroud)
小智 95
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'
Run Code Online (Sandbox Code Playgroud)
现在,如果你有索引页面的链接:你可以使用这个:
<a href={{ url_for('index') }}>Index</a>
Run Code Online (Sandbox Code Playgroud)
你可以用它做很多东西,例如:
@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))
Run Code Online (Sandbox Code Playgroud)
对于上面我们可以使用:
<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a>
Run Code Online (Sandbox Code Playgroud)
像这样你可以简单地传递参数!
小智 34
下面是将js或css链接到模板的其他示例片段.
<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
Run Code Online (Sandbox Code Playgroud)
Muh*_*eed 10
模板:
传递函数名和参数。
<a href="{{ url_for('get_blog_post',id = blog.id)}}">{{blog.title}}</a>
Run Code Online (Sandbox Code Playgroud)
视图、功能
@app.route('/blog/post/<string:id>',methods=['GET'])
def get_blog_post(id):
return id
Run Code Online (Sandbox Code Playgroud)