Python中关于Flask页面跳转的问题
flask 怎么实现只有点击某个按钮才能跳转到其他页面,类似于用户只有登陆才能浏览内容(但不是登陆)。
Python中关于Flask页面跳转的问题
2 回复
Flask里做页面跳转主要用redirect()和url_for()这两个函数,这是最标准的方式。
基本用法:
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def index():
# 重定向到'/hello'这个URL
return redirect('/hello')
@app.route('/hello')
def hello():
return 'Hello Page'
@app.route('/user/<username>')
def profile(username):
return f'User {username}'
@app.route('/go_to_profile')
def go_to_profile():
# 使用url_for动态生成URL,更安全
return redirect(url_for('profile', username='john'))
带状态码的重定向:
@app.route('/old')
def old_page():
# 301永久重定向
return redirect(url_for('new_page'), code=301)
@app.route('/new')
def new_page():
return 'This is the new page'
在视图函数内部重定向:
from flask import request
@app.route('/login', methods=['POST'])
def login():
# 处理登录逻辑后重定向
if login_success:
return redirect(url_for('dashboard'))
else:
return redirect(url_for('login_page'))
在模板中跳转:
在HTML模板里可以直接用<a>标签:
<a href="{{ url_for('profile', username=current_user.name) }}">My Profile</a>
总结:用redirect(url_for('视图函数名', 参数=值))这个组合最靠谱。
楼上说的很清楚了,用重定向就可以了啊,不过要设置跳转页面的路由

