到目前为止,我已经创建了用户对象和登录功能,但我根本不了解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()
答案 0 :(得分:1)
您是否有机会使用SQLAlchemy? 这是我的一个项目的model.py示例,我曾经使用过Sqlite3&amp; Flask登录。
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
希望这有助于为您提供一些线索。
答案 1 :(得分:1)
user_loader回调函数是告诉Flask-Login“如何”从数据库中查找用户ID的一种方法?由于您使用的是sqllite3,因此需要实现user_loader函数来查询sqllite数据库并获取/返回已存储的用户标识/用户名。类似的东西:
@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。
这是流程的工作方式:
通过检查数据库验证用户是否输入了正确的用户名和密码。
如果用户名/密码匹配,则需要从用户ID中检索用户“对象”。您的用户对象可以是userobj = User(userid,email..etc。)。只是实例化它。
通过调用login_user(userobj)登录用户。
重定向无处,闪存等。
答案 2 :(得分:1)
使用SQLAlchemy它可以完全处理所有查询,因此您无需全部编写。
但是如果你继续这样使用它,那么你的user_loader函数应该创建一个“User”类对象。像:
userrow = c.fetchone()
username = userrow[0]
u = User(username=username)
return u