安装shortuuid

pip install shortuuid

编辑front.models.py

from exts import db
import shortuuid
from werkzeug.security import generate_password_hash, check_password_hash
import enum
from datetime import datetime class GenderEnum(enum.Enum):
MALE = 1
FEMALE = 2
SECRET = 3
UNKNOW = 4 class FrontUser(db.Model):
__tablename__ = 'front_user'
#这里的id如果我们还使用自动增长,就会存在商业安全隐患,用户可以根据id推算出我们网站的人数
#不使用自动增长,又要保证id的唯一性,我们就可以使用uuid
#虽然uuid好用,但是它太长了,查找的效率会降低
#这时我们就可以使用shortuuid这个库,它既满足了唯一性,又没有uuid那么长
id = db.Column(db.String(100), primary_key=True, default=shortuuid.uuid)
telephone = db.Column(db.String(11), nullable=False)
username = db.Column(db.String(50), nullable=False)
_password = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(50), unique=True)
realname = db.Column(db.String(50))
avatar = db.Column(db.String(50))
signature = db.Column(db.String(100))
gender = db.Column(db.Enum(GenderEnum), default=GenderEnum.UNKNOW)
join_time = db.Column(db.DateTime, default=datetime.now) #对password对应的是_password,所以要做处理
def __init__(self, *args, **kwargs):
if "password" in kwargs:
self.password = kwargs.get('password')
kwargs.pop("password")
super(FrontUser, self).__init__(*args, **kwargs) @property
def password(self):
return self._password @password.setter
def password(self, newpwd):
self._password = generate_password_hash(newpwd) def check_password(self, rawpwd):
return check_password_hash(self._password, rawpwd)

同步到数据库

python manage.py db migrate
python manage.py db upgrade

然后我可以在manage.py中配置命令来添加前台用户

from apps.front import models as front_models

FrontUser = front_models.FrontUser
... @manager.option('-t', '--telephone', dest='telephone')
@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
def create_front_user(telephone, username, password):
user = FrontUser(telephone=telephone, username=username, password=password)
db.session.add(user)
db.session.commit()
print( '成功创建前台用户:{}'.format(username)) ...

创建一个前台用户

Flask实战第38天:前台模型创建-LMLPHP

查看数据库

Flask实战第38天:前台模型创建-LMLPHP

05-22 03:51