在 Flask 中显示 base.html 中的用户名
Display username in base.html in Flask
我想在 base.html 中添加当前用户名,但我不明白如何添加。
我有用户名,它取自MySQL数据库
#app/routes
@app.route('/auth', methods=['GET', 'POST'])
def auth():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username = request.form['username']
hash = request.form['password']
salt = b'b$Mw/92Q0HkYKTR.0.ghNQs.'
password = bytes(hash, encoding='utf-8')
hash_1 = bcrypt.hashpw(password,salt)
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM user WHERE username = % s AND password = % s', (username, hash_1,))
account = cursor.fetchone()
if account:
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
msg = 'Logged in successfully !'
return render_template('index.html', msg=msg)
else:
msg = 'Неверное имя пользователя/пароль !'
return render_template('auth.html', msg=msg)
当用户登录时,我如何获取用户名字段并将其发送到 base.html?我尝试使用文档来实现它,但它不起作用。
#base.html
{% if g.username %}
<li><span>{{ g.user['username'] }}</span>
{% else %}
<a class="p-2 text-dark" href="/auth">Авторизация</a>
{% endif %}
我做到了
{% if session.loggedin %}
<a class="p-2 text-dark" href="/auth">Привет,{{session.username}} </a>
{% else %}
<a class="p-2 text-dark" href="/auth">Авторизация</a>
我想在 base.html 中添加当前用户名,但我不明白如何添加。
我有用户名,它取自MySQL数据库
#app/routes
@app.route('/auth', methods=['GET', 'POST'])
def auth():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username = request.form['username']
hash = request.form['password']
salt = b'b$Mw/92Q0HkYKTR.0.ghNQs.'
password = bytes(hash, encoding='utf-8')
hash_1 = bcrypt.hashpw(password,salt)
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM user WHERE username = % s AND password = % s', (username, hash_1,))
account = cursor.fetchone()
if account:
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
msg = 'Logged in successfully !'
return render_template('index.html', msg=msg)
else:
msg = 'Неверное имя пользователя/пароль !'
return render_template('auth.html', msg=msg)
当用户登录时,我如何获取用户名字段并将其发送到 base.html?我尝试使用文档来实现它,但它不起作用。
#base.html
{% if g.username %}
<li><span>{{ g.user['username'] }}</span>
{% else %}
<a class="p-2 text-dark" href="/auth">Авторизация</a>
{% endif %}
我做到了
{% if session.loggedin %}
<a class="p-2 text-dark" href="/auth">Привет,{{session.username}} </a>
{% else %}
<a class="p-2 text-dark" href="/auth">Авторизация</a>