Flask-login current_user仅返回ID

时间:2015-06-11 10:25:36

标签: python flask flask-login

我设法让刻录登录工作,但是当我尝试使用时,例如我的模板中的current_user.username值为None

我怀疑这与我的User.get()函数有关,但在我的生活中不能理解我需要做什么,所以我可以访问当前用户usernameemail等等上。

所以问题是,为什么我的current_user属性的其余部分(如username)没有填充?

models.py

注意get函数

from sqlalchemy import Column, Integer, String
from flask_login import UserMixin

from database import Base


class User(Base, UserMixin):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(80), unique=True)
    password = Column(String(80))
    email = Column(String(120), unique=True)

    def __init__(self, id):
        self.id = id

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

    @classmethod
    def get(cls, id):
        """Return user instance of id, return None if not exist"""
        try:
            return cls(id)
        except UserWarning:
            return None

views.py

请注意load_user,我相信烧瓶文档预计会出现这种情况,并且它会将ID作为输入

import flask
from flask_login import login_user, logout_user, login_required

from reportr import app, login_manager
from models import User
from forms import UploadForm, LoginForm
from database import init_session


@login_manager.user_loader
def load_user(id):
    return User.get(id)


@app.route('/', methods=('GET', 'POST'))
def index():
    return flask.render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    del form.email  # Don't want the email address on the form

    if form.validate_on_submit():
        session = init_session()
        user = session.query(User).filter(User.username == flask.request.form['username']).first()

        if user and user.password == flask.request.form['password']:
            login_user(user)
            flask.flash('Logged in successfully.', 'info')
        else:
            flask.flash('Username or password incorrect.', 'error')

            return flask.redirect(flask.url_for('login'))

        return flask.redirect(flask.url_for('index'))
    return flask.render_template('login.html', form=form)


@app.route('/logout')
def logout():
    logout_user()

    return flask.redirect(flask.url_for('index'))


@app.route('/upload/results', methods=('GET', 'POST'))
def upload_results():
    form = UploadForm()

    if not form.validate_on_submit():
            flask.flash('Please fill out all required fields', 'error')

    return flask.render_template('upload_results.html', form=form)


@app.route("/settings")
@login_required
def settings():
    pass

模板/ NAV-一个bar.html

在这里我使用的是current_user.id,这很有用。

{% block navbar %}
<nav class="navbar navbar-default" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <a class="navbar-brand" href="{{ url_for('.index') }}"><span class="glyphicon-play" aria-hidden="true"></span>Reportr!</a>
        </div>
        <div class="navbar-collapse collapse click-nav">
            <ul class="nav navbar-nav no-js">
                <li class="dropdown">
                    <a id='browse_menu' href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Browse <span class="caret"></span></a>
                    <ul class="dropdown-menu" role="menu">
                        <li>
                            <a id='browse_by_project' href="#">By Project</a>
                        </li>
                    </ul>
                <li class="dropdown">
                    <a id='upload_menu' href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Upload <span class="caret"></span></a>
                    <ul class="dropdown-menu" role="menu">
                    <li>
                        <a id='upload_test_results' href="{{ url_for('.upload_results') }}">Test Results</a>
                    </li>
                    </ul>
                </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                {% if current_user.is_authenticated() %}
                <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{ current_user.id }} <span class="caret"></span></a>
                    <ul class="dropdown-menu" role="menu">
                        <li><a href="{{ url_for('.settings') }}">Settings</a></li>
                        <li class="divider"></li>
                        <li><a href="{{ url_for('.logout') }}">Logout</a></li>
                    </ul>
                </li>
                {% else %}
                <li>
                    <a id='login' href="{{ url_for('.login') }}">Login</a>
                </li>
                {% endif %}
            </ul>
      </div>
    </div>
</nav>
{% endblock %}

1 个答案:

答案 0 :(得分:5)

我找到了问题的根源。

我的load_user()函数没有返回用户,而只是填充了id的用户类的实例。

我更改了我的load_user函数来查询表并返回用户的实例,而不是类,现在它正在运行。

见下文:

@login_manager.user_loader
def load_user(user_id):
    try:
        return User.query.get(user_id)
    except:
        return None

我也摆脱了我的模型上的get()函数,因为这不是必需的,而且更简单。