在浏览器输入url地址可以访问到视图函数,如果需要反向获取对应视图的url地址可以用url_for()函数
url_for() 函数用于构建指定函数的 URL。它把函数名称作为第一个参数。它可以接受任意个关键字参数,每个关键字参数对应 URL 中的变量。未知变量 将添加到 URL 中作为查询参数。
为什么不在把 URL 写死在模板中,而要使用反转函数 url_for() 动态构建?
例如,这里我们使用 test_request_context() 方法来尝试使用 url_for() 。 test_request_context() 告诉 Flask 正在处理一个请求,而实际上也许我们正处在交互 Python shell 之中, 并没有真正的请求。
from flask import Flask, escape, url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'index'
@app.route('/login')
def login():
return 'login'
@app.route('/user/<username>')
def profile(username):
return '{}\'s profile'.format(escape(username))
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
运行结果
/
/login
/login?next=%2F
/user/John%20Doe
接口返回数据的时候,获取访问视图的url地址
from flask import Flask, escape, url_for
app = Flask(__name__)
@app.route('/books/<int:id>')
def book_info(id):
return {
"id": id,
"name": "book name",
"url": url_for("book_info", id=id)
}
if __name__ == '__main__':
app.run()
这样我们只需在@app.route()
一个地方维护url地址就可以了。
在模板中可以使用url_for() 函数获取使用特定的 ‘static’ 端点就可以生成相应的 URL
url_for('static', filename='style.css')
这个静态文件在文件系统中的位置应该是 static/style.css 。
2022年第 12期《python接口web自动化+测试开发》课程,9月17号开学!
本期上课时间:2022年9月17号 - 2022年12月17号,周六周日上午9:00-11:00