Python-Flask中的render_template不起作用

问题描述 投票:-1回答:3

我实际上正在使用Flask创建一个应用程序,我遇到了有关我的路由的问题。

我的情况很简单:用户输入一个令牌来验证自己。一旦他点击身份验证,角度HTTP请求就会使用POST将他的令牌发送到Python服务器。在那里,如果他被授予访问权限,则使用render_template显示主页;否则登录会保持不变。

但是,当用户验证自己时,我在命令行上看到POST成功,验证成功但页面只是停留在登录状态,并且没有重定向到主页,好像第二个render_template不起作用。请帮忙!

@app.route('/')
def index():
    if not session.get('logged_in'):
        return render_template('auth.html')  # this is ok.
    else:
        return render_template('index.html')  # this does not work


@app.route('/login', methods=['POST','GET'])
def login():
    tok = request.form['token']

    if (check_token(tok) == "pass"):  # check_token is a function I've implemented
                                      # to check if token is ok=pass, ko=fail
        session['logged_in'] = True
    else:
        flash("wrong token")

    return index()  
python flask routing
3个回答
4
投票

你的login处理程序不应该直接调用index。它应该将redirect返回到索引。

return redirect('/')

或更好:

return redirect(url_for('index'))

0
投票

我在考虑以下问题。

@app.route('/')
def index():
    if not session.get('logged_in'):
        return return redirect(url_for('login'))
    else:
        return render_template('index.html')  

@app.route('/login', methods=['POST','GET'])
def login():
    if request.method = "POST":
        tok = request.form['token']

        if (check_token(tok) == "pass"):  
            session['logged_in'] = True
        return redirect(url_for('index'))

        else:
            flash("wrong token")

    return render_template("login.html")

0
投票

我在我的应用程序中使用Angular JS将请求发送到我的烧瓶服务器,我意识到我的客户端角度JS在渲染页面时遇到困难,因为它只是期待响应。我第一次尝试做.. document.write('response.data')它确实显示了我的主页,但是我的html页面上附带的脚本停止了工作。第二次尝试,我尝试在我的客户端收到响应后重新加载页面,它运行良好。我不知道这是否是最好的方法,但确实有效。

© www.soinside.com 2019 - 2024. All rights reserved.