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'))