自動生成路由
# 1.導入routers模塊
from rest_framework import routers# 2.實例化類
router=routers.SimpleRouter()# 3.注冊
# ('前綴','繼承自ModelViewSet視圖類','別名')
router.register('books7',views.BooksView) # 不要加斜杠# 4.加入
urlpatterns+=router.urls
action使用
裝時期,給ModelViewSet的試圖類,自定義函數,以及路由。
# action 用法
from rest_framework.decorators import action
class BookViewSet(ModelViewSet):queryset = Book.objects.all()serializer_class = BookModelSerializer# methods 第一個參數,傳一個列表,列表中放請求方式# ‘/books/get_1’ 是請求地址。books是ModelViewSet 注冊的路由# detal:True是, 帶pk ,即/books/1/get_1@action(methods=['GET','POST'],detail=False)def get_1(self,request):book=self.get_queryset()[:2]ser=self.get_serializer(book,many=True)return Response(ser.data)
認證
局部認證
1.新寫認證類
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01.models import UserTokenclass MyAuthentication(BaseAuthentication):def authenticate(self, request):# 認證邏輯, 如果認證通過,返回兩個值# 如果認證失敗,拋出AuthenticationFailed異常token=request.GET.get('token')if token:user_token=UserToken.objects.filter(token=token).first()if user_token:return user_token.user,tokenelse:raise AuthenticationFailed('認證失敗')else:raise AuthenticationFailed('請求地址需要帶token')
2.認證邏輯,如使用token,數據庫儲存。
models.py
class User(models.Model):username=models.CharField(max_length=32)password=models.CharField(max_length=32)user_type=models.IntegerField(choices=((1,'超級用戶'),(2,'普通用戶'),(3,'二筆用戶')))class UserToken(models.Model):token=models.CharField(max_length=64)user=models.OneToOneField(to=User,on_delete=models.CASCADE)
views.py
登錄功能
# 認證功能
from app01 import models
import uuidclass LoginView(APIView):def post(self,request):myRespone=MyResponse()username=request.data.get('username')password=request.data.get('password')print(username,password)user=models.User.objects.filter(username=username,password=password).first()if user:# 登陸成功,生成一個隨機及付出token=uuid.uuid4()# 查詢,沒有就新增models.UserToken.objects.update_or_create(defaults={'token':token},user=user)myRespone.msg='登陸成功'myRespone.token=tokenelse:myRespone.status=101myRespone.msg='用戶名或密碼錯誤'return Response(myRespone.get_dic)
視圖類
增加authentication_classes
from rest_framework.viewsets import ViewSetMixinfrom app01.app_auth import MyAuthentication
# ViewSetMixin一定放在前面,重寫as_view方法
class Books6View(ViewSetMixin,GenericAPIView):authentication_classes = [MyAuthentication]def get_all_book(self,request):books = Book.objects.all()book_ser = BookSerializer(books, many=True)return Response(book_ser.data)
全局認證
settings.py
REST_FRAMEWORK={"DEFAULT_AUTHENTICATION_CLASSES":["app01.app_auth.MyAuthentication",]
}
登錄視圖類需要排除認證,在類里寫空列表
authentication_classes = []