Flask-Login为匿名用户打开需要登录的页面

时间:2017-03-28 10:51:30

标签: python flask flask-sqlalchemy flask-login

在我的烧瓶应用程序中,我想在打开登录页面时重定向已登录到成员区域的用户。我正在使用flask-login扩展名。

现在的问题是,匿名用户可以打开成员页面而无需登录,即使它具有需要登录的装饰器。当我检查终端时,我在匿名用户打开的成员页面上收到此错误:

Error on request:
Traceback (most recent call last):
  File "/home/maxwell/py/aqua/lib/python2.7/site-packages/werkzeug/serving.py", line 209, in run_wsgi
    execute(self.server.app)
  File "/home/maxwell/py/aqua/lib/python2.7/site-packages/werkzeug/serving.py", line 200, in execute
    write(data)
  File "/home/maxwell/py/aqua/lib/python2.7/site-packages/werkzeug/serving.py", line 168, in write
    self.send_header(key, value)
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 412, in send_header
    self.wfile.write("%s: %s\r\n" % (keyword, value))
IOError: [Errno 32] Broken pipe

这是我的Flask代码。我只粘贴了我认为必要的部分:

import os

from flask import Flask, render_template, redirect, flash, request, url_for
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from flask_bcrypt import Bcrypt
from flask_debugtoolbar import DebugToolbarExtension
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from forms import LoginForm, RegisterForm
from flask_bootstrap import Bootstrap
from datetime import timedelta


##############
### config ###
##############

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

from models import User, PValue, History, Anonymous

##############
# extensions #
##############

login_manager = LoginManager()
login_manager.init_app(app)
bcrypt = Bcrypt(app)
toolbar = DebugToolbarExtension(app)
bootstrap = Bootstrap(app)

##################
####flask-login###
##################

login_manager.login_view = "login"
login_manager.login_message_category = 'danger'
login_manager.anonymous_user = Anonymous

@login_manager.user_loader
def load_user(user_id):
    return User.query.filter(User.id == user_id).first()

@app.route('/', methods = ['GET','POST'])
def login():
    if current_user.is_authenticated():
        return redirect(url_for('dashboard'))
    form = LoginForm(request.form)
    if request.method == 'POST':
        print("First If")
        if form.validate_on_submit():
            print("Second If")
            user1 = User.query.filter_by(username = form.username.data).first()
            if user1 and bcrypt.check_password_hash(user1.password, request.form['password']):
                login_user(user1)
                flash('You are logged in. Welcome!','success')
                return redirect(url_for('dashboard'))
            else:
                flash('Invalid username and/or password.','danger')
                return render_template('login.html', title = "Please Login", form = form)
    else:
        return render_template('login.html', form=form)

我正在使用current_user.is_authenticated()来检查用户是否已登录。

现在我将登录视图设置为“登录”,因此默认情况下,当匿名用户输入具有需要登录的装饰器的路线时,它应该转到登录路线,但这不会发生。

这是我的models.py包含AnonymousUserMixin对象,其中包含匿名用户的必要返回值:

from views import db
import datetime
from flask_login import UserMixin, AnonymousUserMixin

class User(db.Model, UserMixin):

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, nullable = False)
    password = db.Column(db.String, nullable = False)

    def __init__(self, username = None, password = None):
        self.username = username
        self.password = password

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return self.id

class Anonymous(AnonymousUserMixin):
    def __init__(self):

        print "Exec"

    def is_authenticated(self):
        return False

    def is_active(self):
        return False

    def is_anonymous(self):
        return True

    def get_id(self):
        return None

我无法弄清楚为什么这个破裂的管道错误不断发生。它与已安装的库有关,还是我的代码中有错误?

1 个答案:

答案 0 :(得分:0)

我通过从Anonymous类中删除所有其他方法来解决它。现在我的匿名类只有一个用户名分配给Guest。

class Anonymous(AnonymousUserMixin):
    def __init__(self):
        self.username = 'Guest'

然后检查用户是否已登录我只是把

if current_user is not 'Guest':
        return redirect(url_for('dashboard'))

但我仍然不知道为什么早期的is_authenticated方法不起作用。