一、redirect()用法
作用:重定向到新的url地址
1.直接用,可以是完整url地址
@index_blu.route('/1111')
def test():
return redirect('http://www.baidu.com')
2、可以是定义的url地址,注意不要前面的"/",host地址就为启动文件配置的host地址
@index_blu.route('/3')
def test3():
return redirect('1111') #1111为定义的url地址 host地址/1111
举例说明:
from flask import Blueprint,render_template,redirect
ta=Blueprint('testbl001',__name__)
@ta.route('/method')
def test002():
return 'test111222'
@ta.route('/test')
def testA():
return redirect('method') #重定向参数为定义的url地址
#访问地址/test时,重定向到url地址 host地址/method,这时候返回test111222
@ta.route('/search')
def testB():
return redirect('https://www.baidu.com/') #重定向参数为完整url链接
3、配合url_for()一起来实现重定向,最终效果与直接使用redirect()一样,只是配合url_for()一起来实现重定向更灵活。
@index_blu.route('/2')
def test2():
return redirect(url_for('index.test'))
二、url_for()用法
url_for()函数对于动态构建特定函数的URL非常有用。
url_for()函数接受函数名作为第一个参数(必填),以及一个或多个关键字参数,每个参数对应于URL的变量部分(有则填,没有则不填)。
注意url_for()里面为函数名,如果注册了蓝图,则为蓝图名字.函数名,注意是蓝图名,不是实例化的蓝图对象名。
如下演示:
from flask import Blueprint,redirect,url_for
pa=Blueprint('testbl002',__name__)
@pa.route('/admin')
def hello_admin():
return 'Hello Admin'
@pa.route('/guest/<guest>')
def hello_guest(guest):
return 'Hello %s as Guest' % guest
@pa.route('/user/<name>')
def hello_user(name):
if name =='admin':
return redirect(url_for('testbl002.hello_admin'))
#url_for()里面为函数名,如果注册了蓝图,则为蓝图名字.函数名,注意是蓝图名,不是实例化的蓝图对象名
else:
return redirect(url_for('testbl002.hello_guest', guest = name))
#url_for()里面为函数名,如果注册了蓝图,则为蓝图名字.函数名,注意是蓝图名,不是实例化的蓝图对象名
踩坑: 在使用url_for()时候,如果在函数名前面不加上蓝图名,打开url地址服务端会报错:werkzeug.routing.BuildError: Could not build url for endpoint ‘hello_admin’. Did you mean ‘testbl002.hello_admin’ instead?
解决方法:在使用url_for()的时候,函数名前面加上蓝图名。 不使用url_for()时候不存在此问题。