我尝试在可能的应用程序中使用flask登录:
我的 Controller :
@app.route("/process_log", methods=['POST'])
def process_login():
filled_form = LoginForm(request.form)
if filled_form.validate():
phone = filled_form.phone.data
password = filled_form.password.data
if User.phone_exists(phone) and User.pass_match(phone, password):
user = User.get_by_phone(phone)
login_user(user.get_id)
return redirect(url_for("index"))
else:
return render_template("login.html", form = filled_form, error = u"Не верный логин или пароль")
else:
return render_template("home.html", form = filled_form)
我有一些定义了 Flask 登录 API 所需函数的类
我的用户类别:
from pymongo import MongoClient
from bson.objectid import ObjectId
class User():
client = MongoClient()
db = client['test']
col = db['user']
user_id = None
def __init__(self, dic):
self.dic = dic
def is_authenticated():
return True
def is_anonymous():
return False
def is_active():
return True
def get_id(self):
return unicode(str(self.user_id))
def save(self):
self.user_id = self.col.insert(self.dic)
print "Debug:" + str(self.user_id)
@staticmethod
def _get_col():
client = MongoClient()
db = client['test']
col = db['user']
return col
@staticmethod
def phone_exists(phone):
col = User._get_col()
if col.find_one({'phone': phone}) != None:
return True
else:
return False
@staticmethod
def pass_match(phone, password):
col = User._get_col()
if col.find_one({'phone': phone})['password'] == password:
return True
else:
return False
@staticmethod
def get(userid):
col = User._get_col()
return col.find_one({'_id':userid})
@staticmethod
def get_by_phone(phone):
col = User._get_col()
dic = col.find_one({'phone': phone})
print dic['password']
return User(dic)
如您所见,函数 is_active 已定义(注意:我也尝试通过 self 传递引用)
但我仍然有这个错误AttributeError: 'function' object has no attribute 'is_active'
很抱歉这里的代码太多,但它应该非常简单。
注意:我的项目使用 mongodb。
请帮我找出错误。太感谢了
还有一件事: 我应该向 login_user(....) 提供 Id 还是我的用户对象?
最佳答案
您必须发送到 login_user
User
实例(不是 id
),请参阅:https://github.com/maxcountryman/flask-login/blob/master/flask_login.py#L576 .
所以接下来的代码必须工作:
user = User.get_by_phone(phone)
login_user(user)
关于python-2.7 - Flask登录 'function'对象没有属性 'is_active',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18344564/