繁体   English   中英

Python-Flask中的render_template无法正常工作

[英]render_template in Python-Flask is not working

我实际上是用Flask创建一个应用程序,遇到路由方面的问题。

我的情况很简单:用户输入一个令牌以对其进行身份验证。 一旦他单击authenticate ,一个有角度的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()  

您的login处理程序不应直接调用index 它应该返回到索引的重定向

return redirect('/')

或更好:

return redirect(url_for('index'))

我在想以下。

@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")

我已经在应用程序中使用Angular JS将请求发送到我的Flask服务器,并且我意识到我的客户端Angular JS在呈现页面时遇到了困难,因为它只是期望响应。 我首先尝试做.. document.write('response.data') ,它确实显示了我的主页,但是我在html页面上附加的脚本停止工作。 第二次尝试,我在客户端收到响应后尝试重新加载页面,并且效果很好。 我不知道这是否是最好的方法,但确实有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM