suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Problem mit current_user.username ohne Daten im flask-login

Verwenden Sie flask, um eine Anmeldeseite zu schreiben. Der Code lautet wie folgt:

# -*- 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 %}

Das Problem besteht nun darin, dass nach dem Klicken zum Anmelden der Benutzername nicht auf der Indexseite angezeigt wird. Wie Sie im Bild unten sehen können:

Es fühlt sich an, als hätte login_user den Benutzer nicht erhalten

仅有的幸福仅有的幸福2755 Tage vor862

Antworte allen(2)Ich werde antworten

  • PHPz

    PHPz2017-05-18 11:02:45

    呃,你仔细看看吧,你的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)

    在你的模板里面你用的是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 %}
    

    Antwort
    0
  • 阿神

    阿神2017-05-18 11:02:45

    应该是User.name 和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
        
    

    Antwort
    0
  • StornierenAntwort