Flask路由-重定向

需要了解:Flask路由原理

重定向外部网站

像百度那样,点击一个搜索结果,会跳转到另一个网站,这个功能的术语叫 重定向

from flask import redirect

@app.route('/douban')
def douban():
    return redirect('http://www.douban.com')

重定向静态网页

下面代码只是介绍功能,一般应用场景是:在访问类似淘宝、知乎等网站,发现未登录时,跳转到登录页面

from flask import redirect

@app.route('/login')
def login():
    return redirect('/static/login.html')

重定向内部链接

在有的网站中,注册成功后会跳转到登录页面(此操作很傻^_^),此功能实现如下:

from flask import url_for,redirect

@app.route('/reg')
def reg():
    # 此处的 'index' 是 endpoint,通过 'index' 找到与之相对应的 URL,即 '/'
    url=url_for('index')
    print(url)
    return redirect(url)

注意:
类似这种功能,都要用url_for()函数,根据 endpoint 找到对应的 URL,然后再调用redirect() 重定向

不要直接调用redirect('/') 重定向,因为 原路由的URL 有可能改变,比如在开发时,可能将@app.route('/') 改成@app.route('/index'),此时再调用redirect('/') 重定向 就会报错

url_for()

根据 endpoint 获取 URL。

url_for(endpoint,**values)
参数
  • endpoint:默认为函数名
  • values:参数列表。
    • 默认为url参数
    • _external:如果设置为True,则生成一个绝对路径URL
    • _scheme:一个字符串指定所需的URL方案。_external参数必须设置为True,不然会抛出ValueError。
    • _anchor:如果提供,则将其添加为URL锚点
    • _method:如果提供,则明确指定HTTP方法

获取另一个蓝图的内部链接

url_for('蓝图的第一个参数.endpoint ', 参数)

原文出处:/show_1EF3UNqDh4Dj.html