在Django和Flask中,都可以通过自定义用户模型来扩展默认的用户系统。下面分别介绍它们的方法和步骤。
Django Custom User Model:
models.py
文件,创建一个新的用户模型,继承自AbstractBaseUser
和PermissionsMixin
。例如:from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
settings.py
文件中,设置AUTH_USER_MODEL
为你的自定义用户模型:AUTH_USER_MODEL = 'yourapp.CustomUser'
python manage.py makemigrations
和python manage.py migrate
命令,应用模型更改。Flask User Model Extension:
在Flask中,可以使用Flask-User扩展来轻松扩展用户模型。以下是使用Flask-User的步骤:
pip install flask-user
from flask_user import UserMixin, SQLAlchemyUserDatastore, UserManager
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class CustomUser(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(255), nullable=False)
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary='user_roles')
class Role(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class UserRoles(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE'))
role_id = db.Column(db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))
user_datastore = SQLAlchemyUserDatastore(db, CustomUser, Role)
user_api = UserApi(user_datastore)
user_api
进行用户相关的操作。这样,你就可以根据需要扩展Django和Flask的用户模型了。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。