2

我有一个包含用户和角色的 mysql 表,并且我有一个登录页面。有用。但是,我不知道如何从数据库中查找用户。

1)这是我的用户类和登录表单

class User(UserMixin):
    def __init__(self, email, password, org_role, user_role, id, active=True):
        self.email = email
        self.password = password
        self.org_role = org_role
        self.user_role = user_role
        self.id = id
        self.active = active
    def is_authenticated(self):
        return True
    def is_active(self):
        return True
    def is_anonymous(self):
        return False
    def get_id(self):
        return unicode(self.id)
    def __repr__(self):
        return '<User %r>' % (self.email)


@login_manager.user_loader
def load_user(id):
    return USERS.get(int(id))


@app.route("/login", methods=["GET", "POST"])
def login():
    form = LoginForm()
    if request.method == "POST" and form.validate():
        if form.email.data + form.password.data in USER_NAMES:
            remember = request.form.get("remember", "no") == "yes"
            if login_user(USER_NAMES[form.email.data + form.password.data], remember=remember):
                flash("Logged in!")
                return redirect(request.args.get("next") or url_for("index"))
            else:
                flash(u"Sorry, but you could not log in.")
        else:
            flash(u"Invalid email/password.")
    return render_template("login.html", title = 'Sign In', form = form)

2)这是我不明白的。

我有这个代码:

USERS={}
for i,nn in enumerate(userlist):
    USERS[i+1]=User(nn['email'],nn['password'],nn['org_role'],nn['user_role'],int(nn['user_id']))
USER_NAMES = dict((u.email + u.password, u) for u in USERS.itervalues())

当我启动应用程序时,我有一个 mysql 查询,它填充了所有允许的USERS.

我试图关注来自 flask-login 的文档,但他们没有显示从数据库中查找用户的示例。仅来自预先填充的用户列表。如果我更新表中的用户,除非我重新启动服务器,否则它不会被拾取。

这真的没有意义。任何有关如何从 mysql 数据库中查找用户并将其添加到 User 类的指导都会很棒。

以下是我获取所有用户的代码:

def getUsers():
    conn = MySQLdb.connect(host=db_host,user=db_username,passwd=db_password,db=db_database)
    cursor = conn.cursor()
    #query = """SELECT * from rtb_users WHERE email='%s' and password='%s'""" % (email,user_password)
    query = """SELECT * from rtb_users"""
    cursor.execute(query)

    userlist = []
    rows = cursor.fetchall()
    for row in rows:
        user_id = row[0]
        email = row[1]
        password = row[2]
        first_name = row[3]
        last_name = row[4]
        org_role = row[5]
        user_role = row[6]

        temp = {'user_id':user_id,'email':email,'password':password,'first_name':first_name,'last_name':last_name,'org_role':org_role,'user_role':user_role}
        userlist.append(temp)
    cursor.close()
    conn.close()
    return userlist
userlist = getUsers()
4

1 回答 1

2

每次需要加载用户时只需访问数据库:

@login_manager.user_loader
def load_user(id):
    return get_user(id)

def get_user(user_id):

    # TODO: Return None on ValueError
    user_id = int(user_id)

    conn = MySQLdb.connect(...etc...)
    cursor = conn.cursor()
    user = cursor.fetchone("SELECT * FROM rtb_users WHERE ID = %s", (user_id, ))

    conn.close()

    try:
        # A simpler way to map row names to row values in a dictionary
        user = dict(zip(cursor.description, user))
        user = User(user['email'],
                        user['password'],
                        user['org_role'],
                        user['user_role'],
                        int(user['user_id']))
    except MySQLdb.Error:
        user = None

    return user

最终,您很可能希望在get_user函数上进行缓存(以避免为与服务器建立的每个连接添加数据库调用),但对于测试,这应该可以工作。

于 2012-08-07T02:20:51.777 回答