ViewSet实现登陆验证
views:
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
class Login(ViewSet):
@action(methods=["POST"],detail=False)
def login(self,request):
name=request.data.get('name')
password=request.data.get('password')
user=models.User.objects.filter(username=name,password=password).first()
if user:
token=uuid.uuid4()
models.User.objects.update_or_create(defaults={'token':token},username=name)
return Response(data={'msg':'登陆成功','token':token}, status=200)
else:
return Response('用户名或密码错误',status=401)
urls:
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('',views.Login,basename='login')
urlpatterns += router.urls
token授权
创建验证模块
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .models import User
class LoginAuth(BaseAuthentication):
def authenticate(self,request):
token=request.GET.get('token')
user_token=User.objects.filter(token=token).first()
if token:
# pass
return user_token.username,token
else:
raise AuthenticationFailed('token不合法')
全局生效修改setting
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["exam.auth.LoginAuth",]
}
在不需要进行权限验证的视图加入
authentication_classes = []
permission_classes = []
扩写auth_user表
完成后需要在settings.py 中设置,来覆盖django默认的表
AUTH_USER_MODULE = ’app.User‘
但这时,django的admin不会识别User,需要写入admin.py中注册新的user表
在admin.py中注册User表,并且继承UserAdmin
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from app.models import User
admin.site.register(User,UserAdmin)