您好,登錄后才能下訂單哦!
在Django和Flask中,都可以通過自定義用戶模型來擴展默認的用戶系統(tǒng)。下面分別介紹它們的方法和步驟。
Django Custom User Model:
models.py
文件,創(chuàng)建一個新的用戶模型,繼承自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
文件中,設(shè)置AUTH_USER_MODEL
為你的自定義用戶模型:AUTH_USER_MODEL = 'yourapp.CustomUser'
python manage.py makemigrations
和python manage.py migrate
命令,應(yīng)用模型更改。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
進行用戶相關(guān)的操作。這樣,你就可以根據(jù)需要擴展Django和Flask的用戶模型了。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。