作业
1 继承ModelViewSet,获取所有的,只获取前10条
2 登陆接口,查询图书接口,必须登录后才能查看,token信息放在头里(认证组件),全局使用,局部禁用(login禁用)
3 使用simplerouter自动生成路由
# 模型表:
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5,decimal_places=2)
publish = models.CharField(max_length=32)
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)
# ser.py
from rest_framework.serializers import ModelSerializer
from app01.models import Book
class BookSerializer(ModelSerializer):
class Meta:
model = Book
fields = '__all__'
# app_auth.py
from rest_framework.authentication import BaseAuthentication
from app01 import models
from rest_framework.exceptions import AuthenticationFailed
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
token = request.META.get('HTTP_TOKEN')
if token:
user_token = models.UserToken.objects.filter(token=token)
if user_token:
return user_token.first().user, token
else:
raise AuthenticationFailed('认证失败')
else:
raise AuthenticationFailed('请求头中必须携带token')
# settings
INSTALLED_APPS = [
'rest_framework'
]
staticREST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": ["app01.app_auth.MyAuthentication", ]
}
# 路由:
from django.conf.urls import url
from rest_framework import routers
from app01 import views
router = routers.SimpleRouter()
router.register('books', views.BookViewSet)
urlpatterns = [
url(r'^login/', views.Login.as_view()),
]
urlpatterns += router.urls
# 视图:
from app01 import models
import uuid
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from app01.ser import BookSerializer
from rest_framework.decorators import action
# Create your views here.
class Login(APIView):
authentication_classes = []
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = models.User.objects.filter(username=username, password=password)
if user:
token = uuid.uuid4()
user = user.first()
models.UserToken.objects.update_or_create(defaults={'token': token}, user=user)
return Response({'status': 100, 'msg': '登陆成功','token':token})
else:
return Response({'status': 101, 'msg': '用户名和密码错误'})
class BookViewSet(ModelViewSet):
queryset = models.Book.objects.all()
serializer_class = BookSerializer
print(queryset)
@action(methods=['GET','POST'], detail=True)
def get_many(self, request, pk):
book = self.get_queryset()[:int(pk)]
ser = self.get_serializer(book, many=True)
return Response(ser.data)
1 没有登陆无法获取图书数据:
2 登陆
2 将token 字符串加到请求头中,通过校验,获取图书数据
3 用get_many方法获取指定数量的数据信息: