Flask--url反转和重定向

文章目录

url反转

  • 定义
  • url_for(): 该函数用于构建指定函数的URL,
  • 存在endpoint时,操作对象是endpoint,不存在endpoint时,操作对象是函数
  • 在页面重定向或模版中使用url反转
  • 不带参数的反转
@app.route('/')
def index():
    return str(url_for('index')) # 返回 /
  • 带参数的反转
@app.route('/')
def index():
    return redirect(url_for('hello', id=1, page=1)) # url: 127.0.0.1:5000/hello/1?page=1


@app.route('/hello/<id>')
def hello(id):
    return f'hello {id}'
  • html中用于文件路径定位
<head>
   <meta charset="UTF-8">
   <title>URL</title>
   <link rel="stylesheet" href="{{ url_for('static', filename='/css/base.css') }}">
   <script src="{{ url_for('static', filename='/js/alert.js') }}"></script>
</head>

重定向

  • 方式一:redirect_to参数永久重定向
  • 操作对象只能是path,不能是endpoint
@app.route('/index', redirect_to='hello')
def index():
    return 'index'

@app.route('/hello', endpoint='he')
def hello():
    return 'hello'
  • 方式二:视图中redirect方法
  • 源码中redirect方法默认返回状态302,并且添加"Location"请求头,浏览器会根据"Location"值重新访问

源码

def redirect(location, code=302, Response=None):
    ...
    response.headers["Location"] = location
    return response

示例代码

from flask import Flask, url_for, redirect
 
 
@app.route('/question/<is_login>/')
def question(is_login):
    if is_login == '1':
        return '这是问答页面'
    else:
        return redirect(url_for('login'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值