Issue with current_user.username having no data in flask-login
仅有的幸福
仅有的幸福 2017-05-18 11:00:45
0
2
860

Use flask to write a login page, the code is as follows:

# -*- coding:utf-8 -*-
from flask import Flask,render_template,session,redirect,url_for,flash,request
from flask_login import LoginManager,login_required,UserMixin,login_user,logout_user
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.file import FileField
from flask_wtf import Form
from wtforms import StringField,PasswordField,SubmitField,BooleanField
from wtforms.validators import Required
from werkzeug.security import generate_password_hash,check_password_hash
import pymssql

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost:3306/dh_inf_manage'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'hard to guess string'
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'
login_manager.init_app(app)
db=SQLAlchemy(app)
bootstrap = Bootstrap()
bootstrap.init_app(app)

class NameForm(Form):
    name = StringField(u'用户名:',validators = [Required()])
    password = PasswordField(u'密码:')
    submit = SubmitField('Log In')
    
class LoginForm(Form):
    name = StringField(u'用户名:',validators = [Required()])
    password = PasswordField(u'密码',validators = [Required()])
    submit = SubmitField(u'登陆')
    
class User(UserMixin,db.Model):
    __tablename__ = 'dic_user'
    
    emp_sn = db.Column(db.String(50),primary_key = True)
    name = db.Column(db.String(45))
    password = db.Column(db.String(128))
    emp_dept_sn = db.Column(db.String(45),db.ForeignKey('dic_dept.dept_sn'))
    py_code =  db.Column(db.String(50))
    wb_code =  db.Column(db.String(50))
    autograph = db.Column(db.LargeBinary)
    
    def verify_password(self, password):
        return check_password_hash(self.password, password)
    
    @property 
    def password_hash(self):
        raise AttributeError('password is not a readable attribute')
    
    @password_hash.setter
    def password_hash(self, password):
        self.password = generate_password_hash(password)
        
    def get_id(self):
        return unicode(self.emp_sn)

    def __repr__(self):
        return '<User %r>' % self.name

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
    
@app.route ('/',methods=['GET','POST'])
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()   
    if form.validate_on_submit():
        user = User.query.filter_by(emp_sn = form.name.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user)
            return redirect(url_for('index'))
        flash (u'用户名或密码不正确')
    return render_template('login.html',form = form)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash(u'你已经注销!')
    return redirect(url_for('index'))
 
@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'),404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'),500


if __name__ == '__main__':
    app.run(host = '192.168.199.203',port = 8035,debug = True)

index.html code:

{% extends "base.html" %}

{% block title %}Flasky{% endblock %}

{% block page_content %}
<p class="page-header">
    <h1>Hello, {% if current_user.is_authenticated %}{{ current_user.username }}{% else %}Stranger{% endif %}!</h1>
</p>
{% endblock %}

The problem now is that after clicking to log in, the user name is not displayed on the index page. As you can see in the picture below:

It feels like login_user did not obtain the user

仅有的幸福
仅有的幸福

reply all(2)
PHPzhong

Uh, take a closer look, your model里面的是name,而你的模板里面用的是username:

class User(UserMixin,db.Model):
    __tablename__ = 'dic_user'
    
    emp_sn = db.Column(db.String(50),primary_key = True)
    
    name = db.Column(db.String(45))    //你这里是name
    
    password = db.Column(db.String(128))
    emp_dept_sn = db.Column(db.String(45),db.ForeignKey('dic_dept.dept_sn'))
    py_code =  db.Column(db.String(50))
    wb_code =  db.Column(db.String(50))
    autograph = db.Column(db.LargeBinary)

In your template you use username:

{% extends "base.html" %}

{% block title %}Flasky{% endblock %}

{% block page_content %}
<p class="page-header">
    {# 这下面应该改成current.name #}
    <h1>Hello, {% if current_user.is_authenticated %}{{ current_user.username }}{% else %}Stranger{% endif %}!</h1>
</p>
{% endblock %}
阿神

It should be caused by the inconsistency between User.name and current_user.username!

class User(UserMixin,db.Model):
    __tablename__ = 'dic_user'
    
    emp_sn = db.Column(db.String(50),primary_key = True)
    name = db.Column(db.String(45))
    password = db.Column(db.String(128))
    emp_dept_sn = db.Column(db.String(45),db.ForeignKey('dic_dept.dept_sn'))
    py_code =  db.Column(db.String(50))
    wb_code =  db.Column(db.String(50))
    autograph = db.Column(db.LargeBi<p class="page-header">

    <h1>Hello, {% if current_user.is_authenticated %}{{ current_user.username }}{% else %}Stranger{% endif %}!</h1>
</p>nary
    
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template