使用 url_for() 在 Flask 中创建动态 URL
- 2025-02-14 09:50:00
- admin 原创
- 55
问题描述:
我的一半 Flask 路由都需要一个变量,例如,/<variable>/add
或/<variable>/remove
。如何创建到这些位置的链接?
url_for()
函数路由到一个参数,但是我无法添加参数?
解决方案 1:
它采用变量的关键字参数:
url_for('add', variable=foo)
url_for('remove', variable=foo)
flask-server 具有以下功能:
@app.route('/<variable>/add', methods=['GET', 'POST'])
def add(variable):
@app.route('/<variable>/remove', methods=['GET', 'POST'])
def remove(variable):
解决方案 2:
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>
你可以用它做很多事情,例如:
# int has been used as a filter so that only integer can be passed in the url, otherwise it will give a 404 error
@app.route('/questions/<int:question_id>')
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>
这样你就可以简单地传递参数!
解决方案 3:
请参阅Flask API 文档flask.url_for()
下面是将 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') }}">
解决方案 4:
模板:
传递函数名称和参数。
<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
解决方案 5:
您需要添加函数意味着您想要呈现该函数的页面应该添加到 url_for(函数名称)中。它将重定向到该函数,并且页面将相应地呈现。
解决方案 6:
如果这有帮助,您可以在声明 flask 应用程序时覆盖静态文件夹。
app = Flask(__name__,
static_folder='/path/to/static',
template_folder='/path/to/templates')
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD