为什么我的代码会跳过我的索引页?

why is my code skipping my index page?

每当我进入登录站点 (0.0.0.0:5000/) 时,页面立即恢复为 0.0.0.0:5000/admin。关于为什么会发生这种情况的任何想法?

运行 通过英特尔爱迪生上的 yocto。通过腻子编辑

@app.errorhandler(404)
@app.errorhandler(500)
def errorpage(e):
    return render_template('404.html')

def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('please login first.')
            return redirect (url_for('index'))
    return wrap

@app.route('/', methods=['GET','POST'])
def index():
    error = None
    if  request.method == 'POST':
        if request.form['username'] != 'admin' or request.form['password'] != 'password':
            error = 'invalid attempt.'

    else:
        session['logged_in'] = True
        return redirect(url_for('admin'))
    return render_template('index.html', error = error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    return render_template('/logout.html')

@app.route('/admin',methods=['GET','POST'])
@login_required
def admin():

看起来只要有人用GET点击页面,它就会被设置为logged_in = True并重定向到/admin

@app.route('/', methods=['GET','POST'])
def index():
    error = None
    if  request.method == 'POST':
        if request.form['username'] != 'admin' or request.form['password'] != 'password':
            error = 'invalid attempt.'

    else: # this is always triggered for GETs, even if not logged in!
        session['logged_in'] = True
        return redirect(url_for('admin'))
    return render_template('index.html', error = error)

相反,您应该检查他们是否已经登录,并在检查凭据后在 POST 块中设置 logged_in 属性。

实际上,看起来您的 else 块上的缩进是关闭的:

@app.route('/', methods=['GET','POST'])
def index():
    error = None
    if  request.method == 'POST':
        if request.form['username'] != 'admin' or request.form['password'] != 'password':
            error = 'invalid'
        else: # this indenting should work now
            session['logged_in'] = True
            return redirect(url_for('admin'))

    return render_template('index.html', error = error)