路由
1 在urls.py中配置 (当视图类继承了 ViewSetMixin, 路由的写法)
path('books/', views.BookViewSet.as_view({'get':'list', 'post':'create'})),
re_path('books/(?P<pk>\d+)', views.BookViewSet.as_view({'get':'retrieve', 'put':'update', 'delete':'destroy'})),
自动生成路由
urls.py
from rest_framework import routers
router = routers.SimpleRouter()
router.register('books', views.BookViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
]
urlpatterns+=router.urls
viwes.py
from rest_framework.viewsets import ModelViewSet
from app01.models import Book
from app01.ser import BookSerializer
class BookViewSet(ModelViewSet):
queryset = Book.objects
serializer_class = BookSerializer
action的使用
action干什么用的? 为了给继承自ModelViewSet的视图类中定义的函数也添加路由
怎么用?
class BookViewSet(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
@action(methods=['GET'], detail=True)
def get_1(self, request, pk):
print(pk)
book = self.get_queryset()[:2]
ser = self.get_serializer(book, many=True)
return Response(ser.data)
认证
# 认证的实现
1 写一个类, 继承BaseAuthentication, 重写authenticate, 认证逻辑都写在这里面
2 全局使用, 局部使用
认证组件的使用
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01.models import UserToken
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
token = request.GET.get('token')
if token:
user_token = UserToken.objects.filter(token=token).first()
if user_token:
return user_token.user, token
else:
raise AuthenticationFailed('认证失败')
else:
raise AuthenticationFailed('请求地中需要携带token')
全局使用 在 settings.py 中配置 可以有多个认证, 从左到右依次执行
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",]
}
局部使用, 在视图类上写
authentication_classes = [MyAuthentication]
局部禁用
authentication_classes = []
权限的使用
写一个类, 继承BasePermission, 重写has_permission,如果权限通过就返回True, 不通过就返回False
from rest_framework.permissions import BasePermission
class UserPermission(BasePermission):
def has_permission(self, request, view):
user = request.user
print(user.get_user_type_display())
if user.user_type == 1:
return True
else:
return False
局部使用
class TestView(APIView):
authentication_classes = [MyAuthentication]
permission_classes = [UserPermission]
全局使用
REST_FRAMEWORK={
"DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",],
'DEFAULT_PERMISSION_CLASSES': [
'app01.app_auth.UserPermission',
],
}
局部禁用
class Test2View(APIView):
permission_classes = []