7

到目前为止,我创建了用户对象和登录功能,但我根本不了解 user_loader 部分。我很困惑,但这是我的代码,请指出正确的方向。

@app.route('/login', methods=['GET','POST'])
def login():
    form = Login()
    if form.validate():
        user=request.form['name']
        passw=request.form['password'] 
        c = g.db.execute("SELECT username from users where username = (?)", [user])
        userexists = c.fetchone()
        if userexists:
            c = g.db.execute("SELECT password from users where password = (?)", [passw])
            passwcorrect = c.fetchone()
            if passwcorrect:
                #session['logged_in']=True
                #login_user(user)
                flash("logged in")
                return redirect(url_for('home'))
            else:
                return 'incorrecg pw'
        else:
            return 'fail'
    return render_template('login.html', form=form)

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('home'))

我的用户

class User():

    def __init__(self,name,email,password, active = True):
        self.name = name
        self.email = email
        self.password = password
        self.active = active

    def is_authenticated():
        return True
        #return true if user is authenticated, provided credentials

    def is_active():
        return True
        #return true if user is activte and authenticated

    def is_annonymous():
        return False
        #return true if annon, actual user return false

    def get_id():
        return unicode(self.id)
        #return unicode id for user, and used to load user from user_loader callback

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

    def add(self):
        c = g.db.execute('INSERT INTO users(username,email,password)VALUES(?,?,?)',[self.name,self.email,self.password])
        g.db.commit()

我的数据库

import sqlite3
import sys
import datetime

conn = sqlite3.connect('data.db')#create db

with conn:
    cur = conn.cursor()
    cur.execute('PRAGMA foreign_keys = ON')
    cur.execute("DROP TABLE IF EXISTS posts")
    cur.execute("DROP TABLE IF EXISTS users")
    cur.execute("CREATE TABLE users(id integer PRIMARY KEY, username TEXT, password TEXT, email TEXT)")
    cur.execute("CREATE TABLE posts(id integer PRIMARY KEY, body TEXT, user_id int, FOREIGN KEY(user_id) REFERENCES users(id))")

我还在我的init中设置了 LoginManager 。我不确定下一步该做什么,但我知道我必须了解如何设置它

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

如何调整此部分代码以适用于我的数据库?

编辑:如果这看起来正确或可以改进,请告诉我:)

 @login_manager.user_loader
    def load_user(id):
        c = g.db.execute("SELECT id from users where username = (?)", [id])
        userid = c.fetchone()
        return userid

    @app.route('/login', methods=['GET','POST'])
    def login():
        form = Login()
        if form.validate():
            g.user=request.form['name']
            g.passw=request.form['password'] 
            c = g.db.execute("SELECT username from users where username = (?)", [g.user])
            userexists = c.fetchone()
            if userexists:
                c = g.db.execute("SELECT password from users where password = (?)", [g.passw])
                passwcorrect = c.fetchone()
                if passwcorrect:  
                user = User(g.user, 'email', g.passw)
                login_user(user)
                flash("logged in")              
                return redirect(url_for('home'))
            else:
                return 'incorrecg pw'
        else:
            return 'fail'
    return render_template('login.html', form=form)

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('home'))
import sqlite3
from flask import g

class User():

    def __init__(self,name,email,password, active = True):
        self.name = name
        self.email = email
        self.password = password
        self.active = active

    def is_authenticated(self):
        return True
        #return true if user is authenticated, provided credentials

    def is_active(self):
    return True
    #return true if user is activte and authenticated

def is_annonymous(self):
    return False
    #return true if annon, actual user return false

def get_id(self):
    c = g.db.execute('SELECT id from users where username = (?)', [g.user])
    id = c.fetchone()
    return unicode(id)
    #return unicode id for user, and used to load user from user_loader callback

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

def add(self):
    c = g.db.execute('INSERT INTO users(username,email,password)VALUES(?,?,?)',[self.name,self.email,self.password])
    g.db.commit()
4

3 回答 3

1

您是否有机会使用 SQLAlchemy?这是我不久前使用 Sqlite3 和 Flask 登录的项目的 model.py 示例。

USER_COLS = ["id", "email", "password", "age"]

你创造了一个引擎?

engine = create_engine("sqlite:///ratings.db", echo=True)

session = scoped_session(sessionmaker(bind=engine, autocommit=False, autoflush=False))
Base = declarative_base()
Base.query = session.query_property()
Base.metadata.create_all(engine)

这是用户类的示例:

class User(Base):
    __tablename__ = "Users"

    id = Column(Integer, primary_key = True)
    email = Column(String(64), nullable=True)
    password = Column(String(64), nullable=True)
    age = Column(Integer, nullable=True)

    def __init__(self, email = None, password = None, age=None):
        self.email = email
        self.password = password
        self.age = age

希望这有助于给你一点线索。

于 2013-05-09T19:31:35.380 回答
1

user_loader 回调函数是一种告诉 Flask-Login “如何”从数据库中查找用户 ID 的方法?由于您使用的是 sqllite3,因此您需要实现 user_loader 函数来查询您的 sqllite 数据库并获取/返回您存储的用户 ID/用户名。就像是:

@login_manager.user_loader
def load_user(id):
    c = g.db.execute("SELECT username from users where username = (?)", [id])
    userrow = c.fetchone()
    userid = userrow[0] # or whatever the index position is
    return userid

当您调用 login_user(user) 时,它会调用 load_user 函数来计算用户 ID。

这就是流程的工作方式:

  1. 您通过检查数据库来验证用户是否输入了正确的用户名和密码。

  2. 如果用户名/密码匹配,那么您需要从用户 ID 中检索用户“对象”。您的用户对象可能是 userobj = User(userid,email..etc.)。只需实例化它。

  3. 通过调用 login_user(userobj) 登录用户。

  4. 重定向到任何地方,闪存等。

于 2013-05-09T20:44:07.747 回答
1

使用 SQLAlchemy 它完全为您处理所有查询,因此您不必全部写出来。

但是如果你继续以这种方式使用它,那么你的 user_loader 函数应该创建一个“用户”类对象。像:

userrow = c.fetchone()
username = userrow[0]
u = User(username=username)
return u
于 2013-05-13T20:37:39.727 回答