2023年6月23日发(作者:)
在Django中,⾃定义User模型,使⽤token鉴权,实现注册、登录、修改密码等API在Django中,⾃定义User模型,实现注册、登录、修改密码、登出、⾸页5个API。⼤体步骤是:⾃定义User模型->重构鉴权后台->settings设置->views修改->Postman测试。1、在中,仿照Django官⽹提供的样例,⾃定义User模型,主要是增加了phone这个必选字段。代码如下:from import modelsfrom import ( BaseUserManager, AbstractBaseUser)class CustomUserManager(BaseUserManager): def create_user(self, user_id, phone, email=None, password=None): """ Creates and saves a User with the given phone,.... """ if not phone: raise ValueError('phone must be given when create user') if email: email = ize_email(email) user = ( user_id = user_id, phone = phone, email = email, ) _password(password) (using=self._db) return user def create_superuser(self, user_id, phone=None, email=None, password=None): user = _user( user_id, phone=phone, email=email, password=password, ) _admin = True (using=self._db) return userclass CustomUser(AbstractBaseUser): user_id = eld( max_length=30, unique=True, ) phone = eld( max_length=30, null=True, blank=True, unique=True, default=None, ) email = ield( verbose_name='email address', max_length=255, unique=True, null=True, blank=True, ) is_active = nField(default=True) is_admin = nField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'user_id' REQUIRED_FIELDS = ['phone'] def __str__(self): return _id def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return _admin # 是admin的话,就是雇员 2、在app⽬录下,新建⽂件,仿照Django官⽹提供的样例(还是上⾯给出的⽹址),写出⾃定义的CustomBackend(⾃定义的鉴权后台):from .models import CustomUser as Userclass CustomBackend: def authenticate(self, request, user_id=None, phone=None, password=None, **kwargs): # ⽀持后台登录功能,因为admin登录提交的时候会发送username字段 if user_id is None: user_id = ('username') try: if phone: user = (phone=phone) elif user_id: user = (user_id=user_id) if _password(password): return user except tExist: return None return None def get_user(self, user_id): try: return (pk=user_id) except tExist: return None3、在settings中设置:(1)要使⽤⾃定义的User模型和鉴权后台:# Custom UserAUTH_USER_MODEL = 'chat_User'# Custom Authentication backendAUTHENTICATION_BACKENDS = ['chat_Backend'](2)确定使⽤token鉴权:INSTALLED_APPS = [ ...... 'rest_framework', 'rest_ken', 'chat_user',] 4、修改,实现注册、登录、修改密码、登出、⾸页5个API(前4个是post⽅式,最后⼀个是get⽅式):import uuidfrom uts import renderfrom b import authfrom rest_framework import statusfrom rest_se import Responsefrom rest_ import APIViewfrom rest_tication import BasicAuthentication,SessionAuthentication,TokenAuthenticationfrom rest_ import Tokenfrom rest_sions import AllowAny,IsAuthenticatedfrom .models import CustomUser as Userclass Register(APIView): def post(self, request): """ 注册 """ phone = ('phone') password = ('password') user_id = 4().hex user = _user(user_id=user_id, phone=phone, password=password) () context = { "status": _200_OK, "msg": "⽤户注册成功" } return Response(context)class Login(APIView): authentication_classes = (BasicAuthentication,TokenAuthentication) # 使⽤基础的和token的验证⽅式 permission_classes = (AllowAny,) # 允许所有⼈访问 def post(self, request): """ 登录 """ phone = ('phone') password = ('password') user = ticate(request, phone=phone, password=password) if user: (request, user) token = (user=user) context = { "status": _200_OK, "msg": "⽤户登录成功", "user_id":_id, "token":, } else: context = { "status": _403_FORBIDDEN, "msg": "⽤户名或密码错误", } return Response(context)class Logout(APIView): authentication_classes = (BasicAuthentication,TokenAuthentication) permission_classes = (IsAuthenticated,) def post(self, request): """ 登出 """ #(request) (user=).delete() context = { "status": _200_OK, "msg": "退出成功" } return Response(context)class Password(APIView): authentication_classes = (BasicAuthentication,TokenAuthentication) # 使⽤基础的和token的验证⽅式 permission_classes = (IsAuthenticated,) # 只允许所有通过鉴权的⼈访问 def post(self, request): """ 修改密码 """ new_password1 = ('new_password1') new_password2 = ('new_password2') if new_password1 and new_password1 == new_password2: _password(new_password1) () context = { "status": _200_OK, "msg": "修改密码成功" } else: context = { "status": _403_FORBIDDEN, "msg": "两次密码不⼀样或没密码" } return Response(context)class Index(APIView): authentication_classes = (BasicAuthentication,TokenAuthentication) # 使⽤基础的和token的验证⽅式 permission_classes = (IsAuthenticated,) # 只允许所有通过鉴权的⼈访问 def get(self,request): context = { "data":"Hello World!", "status":200, "msg":"访问index成功" } return Response(context)5、确认urls已配置好,包括项⽬的urls和应⽤的urls,下⾯列出的仅是应⽤的urls:from import path, include, re_pathfrom . import viewsurlpatterns = [ path('register/', _view()), path('login/', _view()), path('logout/', _view()), path('password/', _view()), path('index/', _view()),]6、写⼊数据库:python makemigrationspython migrate在写⼊的时候可能会报错,ityError: UNIQUE constraint failed,是因为之前数据库中有user的数据,⽽表结构不⼀样,删除原来的⽤户数据再写⼊就⾏;我是删除了整个sqlite数据库,重新写⼊数据库。
7、开启服务(python runserver),⽤Postman测试各个接⼝,成功。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1687516644a16277.html
评论列表(0条)