问题描述
我想在base.html中添加当前的用户名,但我不知道该怎么做。
#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'$2b$12$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>