在我的表中,用户具有类似admin / client的角色。 https://imgur.com/Q53688B,我想在html标签中显示他们的角色
app = Flask(__name__)
app.secret_key = "mysecretkey"
app.config["MYSQL_HOST"] = "localhost"
app.config["MYSQL_USER"] = "root"
app.config["MYSQL_PASSWORD"] = ""
app.config["MYSQL_DB"] = "blog"
app.config["MYSQL_CURSORCLASS"] = "DictCursor"
mysql = MySQL(app)
class LoginForm(Form):
username = StringField("Username:")
password = PasswordField("Password:")
@app.route("/login", methods = ["GET", "POST"])
def login():
form = LoginForm(request.form)
if request.method == "POST":
username = form.username.data
password_entered = form.password.data
cursor = mysql.connection.cursor()
sorgu = "SELECT * FROM users WHERE username = %s AND role = %s"
result = cursor.execute(sorgu, (username,role))
if result > 0:
data = cursor.fetchone()
real_password = data["password"]
role = cursor.fetchone()
user_role = role["role"]
if sha256_crypt.verify(password_entered, real_password):
flash("successfully logged in", "success")
session["logged_in"] = True
session["username"] = username
session["role"] = role
return redirect(url_for("index"))
else:
flash("wrong password", "danger")
return redirect(url_for("login"))
else:
flash("there is no user", "danger")
return redirect(url_for("login"))
return render_template("login.html", form=form)
我想这样在我的dashboard.html中显示角色;
<small>Welcome {{session["username"]}}</small>
<small>Role: {{session["role"]}}</small>
当我尝试登录时,这就是我得到的:“ UnboundLocalError:分配前引用了本地变量'role'”
答案 0 :(得分:0)
您正在使用变量role
,然后在以下位置分配任何值:
sorgu = "SELECT * FROM users WHERE username = %s AND role = %s"
result = cursor.execute(sorgu, (username,role))
我想您要做的只是:
sorgu = "SELECT * FROM users WHERE username = %s"
result = cursor.execute(sorgu, (username,))
答案 1 :(得分:0)
我只添加user_role
t-set
我将其添加到会话中
data = cursor.fetchone()
real_password = data["password"]
user_role = data["role"]
我可以以html格式显示
session["role"] = user_role
已解决