class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(255))
last_name = db.Column(db.String(255))
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
用户模型新增方法
def set_password(self, password):
self.password = hash_password(password)
在用户视图modelview中使用on_model_change方法
class MyUserView(MyModelView):
# 用户管理
def on_model_change(self, form, model, is_created):
model.set_password(form.password.data)
# 使用flask-security 的加密方法 hash_password 对明文明码进行加密
return model
致此解决了
同样的方法,咱们可以处理,更新和创建 时间
# 自动设置created_at updated_at 字段
def on_model_change(self, form, model, is_created):
try:
# print(hasattr(model,'created_at'),hasattr(model,'updated_at'))
if hasattr(model,'created_at') and hasattr(form, 'created_at') and not form.created_at.data:
# 判断存在属性 且表单有此项并为空,咱们给它赋值当前时间,同样处理updated_at字段
model.created_at = datetime.now()
if hasattr(model,'updated_at') and hasattr(form, 'updated_at') and not form.updated_at.data:
model.updated_at = datetime.now()
except Exception as e:
print(e)