DRF 之路由
基本使用
自动生成路由
from rest_framework.routers import DefaultRouter, SimpleRouter
router = SimpleRouter()
router.register('books', views.BookView, basename='books')
router.register('publish', views.PublishView, basename='publish')
router.register('test', views.TestView, basename='testview')
print(router.urls)
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('', include(router.urls)),
]
urlpatterns += router.urls
actions
class TestView(GenericViewSet):
'''action参数
methods:做一个映射,就是http的请求方式,就会映射当前方法
detail:True 或 False
- test/login/
- ^test/pk/login
url_path:访问的路径,可以不写,如果不写,以方法名作为路径 通过 get 请求访问这个路径 test/login 就能触发 login 的执行
url_name:别名
'''
queryset = Book.objects.all()
serializer_class = BookSerializer
def get_serializer_class(self):
if self.action=='login':
return PublishSerializer
else:
return self.serializer_class
@action(methods=['GET'],detail=True)
def login(self, request,pk):
print(self.action)
print(pk)
return Response('登录成功')
router.register('test', views.TestView, basename='testview')
DRF 之认证功能
判断用户是否登录
某个接口登录后才能访问,需要使用认证功能
登录功能
class LoginView(ViewSet):
authentication_classes = []
@action(methods=['POST'], detail=False)
def login(self, request):
name = request.data.get('name')
password = request.data.get('password')
user=User.objects.filter(name=name,password=password).first()
if user:
token=str(uuid.uuid4())
UserToken.objects.update_or_create(defaults={'token':token},user=user)
return Response({'code':100,'msg':'登录成功','token':token})
else:
return Response({'code':101,'msg':'用户名或密码错误'})
认证类
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .models import UserToken
class LoginAuth(BaseAuthentication):
def authenticate(self, request):
token = request.GET.get('token')
user_token = UserToken.objects.filter(token=token).first()
if user_token:
return user_token.user, token
else:
raise AuthenticationFailed('token不合法或没有迭代token')
认证类的使用
from app01.auth import LoginAuth
class PublishView(ModelViewSet):
authentication_classes = [LoginAuth,]
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.auth.LoginAuth",]
}
DRF 之权限
from rest_framework.permissions import BasePermission
class PermissionUser(BasePermission):
def has_permission(self, request, view):
if request.user.user_type == 1:
return True
else:
return False
局部和全局使用
from app01.auth import LoginAuth
class PublishView(ModelViewSet):
permission_classes = [PermissionUser]
REST_FRAMEWORK={
"DEFAULT_PERMISSION_CLASSES":["app01.auth.PermissionUser",]
}