我有一个包含用户和角色的 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()