Flask:如何重定向到具有相同地址但内容不同的同一页面?

Flask: How do you redirect to the same page with the same address, but with different content?

我创建了一个使用数据库进行简单登录的网站。我想要它,这样当你访问主页时,它会提示你签名up/login;当您登录时,它会重定向到同一主页,但主页不得显示提示(暗示您已经登录),而是显示仅供登录用户使用的内容。所以它的路由肯定还是“/”。我试过这个:

<meta http-equiv="refresh" content="0; url={{ url_for('index', authenticated=1) }}">

在我的 Python 文件中:

build = Flask(__name__)
@build.route('/')
def index(authenticated=0):
    if authenticated == 0:
        return render_template("index.html")
    elif authenticated == 1:
        return render_template("main.html")

为什么我希望它变成那样?好吧..我不想让新用户访问那个独家link。因此,除非有一种解决方法,其中独占 link 检测新用户是否未登录,否则我不知道有任何其他方法可以完成此操作

您也可以通过创建两条不同的路线来做到这一点。

举个例子,这里的admin路由是给登录用户的,home是给普通用户的。如果用户通过身份验证,它将重定向到 admin func.

@app.route("/login", methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
            return redirect(url_for('admin'))
        else:
            return redirect(url_for('home'))

@app.route("/admin")
def admin():
    return render_template('admin_home.html')

@app.route("/home")
def home():

    return render_template('home.html')

您必须像这样使用重定向:

from flask import Flask, redirect, render_template

app = Flask(__name__)

@app.route("/")
def index():
    if authenticated == 0:   
        return redirect('/login')
    return render_template("index.html")

@app.route("/login")
def login():
    if authenticated == 1:   
        return redirect('/')
    return render_template("index.html")

我解决了。对于正在阅读本文的其他人,这是我的解决方案: 首先你需要导入 flask_login 并且你必须安装它,你可以通过 pip install flask_login 来完成。 然后,在您的 python 文件中,您需要导入这些:

from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user

之后,创建您的 app 并配置您的 flask_login:

app= Flask(__name__)
db = SQLAlchemy(app) # this is my database file, if you've already created it than you can leave it out
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login' # REPLACE login WITH YOUR LOGIN ROUTE, BUT DO NOT INCLUDE A SLASH (/) AND MUST BE IN QUOTES
login_manager.login_message = "You must be logged-in in order to view this page." # OPTIONAL: A CUSTOM FLASH MESSAGE THAT WILL BE SHOWN WHEN A SIGNED-OUT USER TRIES TO ACCESS PAGES THAT REQUIRE A LOGIN. YOU CAN DELETE IT IF YOU WANT THE DEFAULT MESSAGE

@login_manager.user_loader
def user(id):
    return Clients.query.get(int(id)) # REPLACE Clients WITH YOUR USER CLASS THAT IS USED TO AUTHENTICATE (NORMALLY IT INHERITS A DATABASE MODEL AND USERMIXIN)

最后,滚动到要限制的函数并应用 @login_required 装饰器(从 flask_login 导入),它必须在 @app.route()[=28= 之后]

@app.route('/exclusive_page_for_logged_in_users')
@login_required
def exclusive_page():
    return render_template('exclusive_page.html')

然后回答我原来的问题:

@build.route('/')
def index():
    if current_user.is_authenticated:
        return render_template("index.html")
    else:
        return render_template("authenticate.html")

可以看到条件current_user.is_authenticated。不要替换任何东西,因为这就是它的本意。该条件检查用户是否已登录,如果您未登录,它会加载 authenticate.html 而不是 index.html,同时保持相同的路线;因此你看不到 @login_required 装饰器。

现在,您如何登录?您可以使用 login_user(YOUR_USER_INFO_FROM_DB) 这很简单,但你需要一个数据库来做到这一点。您可以在您的数据库中搜索信息以验证它们,我不会在此处包含这些信息。

pw_check_validation = Clients.query.filter_by(auth_name=auth_name).first()

login_user(pw_check_validation)

flash(f"Login successful.")
return redirect(url_for("index"))

要注销,一个简单的 logout_user() 就可以了。

# My code for log out    
@build.route("/end_session/?db_ID=<int:id>")
@login_required
def logout(id):
    logout_user()
    flash("You have been logged out.")
    return redirect(url_for('authenticate'))

希望这对遇到同样问题的人有所帮助!