Flask重置密码报错:'dict'对象无get_reset_password_token属性
解决AttributeError: 'dict' object has no attribute 'get_reset_password_token'错误
错误原因
你通过mycol.find_one()从MongoDB查询到的user是字典对象,而get_reset_password_token是你自定义User类的实例方法——只有User类的实例才能调用这个方法,直接对字典调用该方法自然会触发属性不存在的错误。
修复步骤
1. 将查询结果转为User类实例
修改路由代码,把MongoDB返回的字典包装成User类的实例:
@app.route('/passwordreset', methods=['GET', 'POST']) def passwordreset(): if current_user.is_authenticated: return redirect(url_for('profile')) form = ResetPasswordRequestForm() if form.validate_on_submit(): # 先拿到字典格式的用户数据 user_dict = mycol.find_one({"email": form.email.data}) if user_dict: # 转为User类实例 user = User(user_dict) EmailSender(form.email.data, "Password reset", {"url": url_for("reset_password", token=user.get_reset_password_token(), _external=True)}, 6) return redirect(url_for('homepage')) flash('If an account with this email was registered please check your email.') return render_template('reset_password_request.html', title='Reset Password', form=form)
2. 修正User类中的两处问题
你的User类还有两个和MongoDB适配的问题,一起修复:
# 需要导入MongoDB的ObjectId解析工具 from bson.objectid import ObjectId from time import time class User(UserMixin): def __init__(self, user_json): self.user_json = user_json def get_id(self): object_id = self.user_json.get('_id') return str(object_id) def get_reset_password_token(self, expires_in=600): return jwt.encode( # 替换self.id为正确的get_id()方法 {'reset_password': self.get_id(), 'exp': time() + expires_in}, app.config['SECRET_KEY'], algorithm='HS256') @staticmethod def verify_reset_password_token(token): try: user_id = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] except: return None # 替换SQLAlchemy风格的查询为MongoDB查询,再转为User实例 user_dict = mycol.find_one({"_id": ObjectId(user_id)}) return User(user_dict) if user_dict else None
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

