0

我想在 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'$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 %}
4

1 回答 1

1

我做到了

{% if session.loggedin %}
      <a class="p-2 text-dark" href="/auth">Привет,{{session.username}} </a>
      {% else %}
      <a class="p-2 text-dark" href="/auth">Авторизация</a>
于 2020-10-20T07:30:53.760 回答