Django---drf路由、认证---作业
1 继承ModelViewSet,获取所有的,只获取前10条
2 登陆接口,查询图书接口,必须登录后才能查看,token信息放在头里(认证组件),全局使用,局部禁用(login禁用)
3 使用simplerouter自动生成路由
views.py
from django.shortcuts import render from rest_framework.authentication import BaseAuthentication import uuid from rest_framework.decorators import action from rest_framework.viewsets import ModelViewSet from rest_framework.views import Response, APIView from app01.models import Book from app01.ser import BookSerializer from app01 import models # Create your views here. class BooksViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer
#获取前10条数据 @action(methods=['get'],detail=False) def get_10(self,request): book = self.get_queryset()[:10] ser = self.get_serializer(book,many=True) return Response(ser.data) class LoginView(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).first() if user: token = uuid.uuid4() print(token) models.UserToKen.objects.update_or_create(defaults={'token':token},user=user) return Response({'status':'100','msg':'登录成功','token':token}) else: return Response({'status':'101','msg':'用户名或密码错误'})
models.py
from django.db import models # Create your models here. class Book(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) price = models.DecimalField(max_digits=9,decimal_places=2) publish = models.CharField(max_length=32) class User(models.Model): username = models.CharField(max_length=64) password = models.CharField(max_length=64) user_type = models.IntegerField(choices=((1, '超级用户'), (2, '普通用户'), (3, '不充值用户'))) class UserToKen(models.Model): user = models.OneToOneField(to=User,on_delete=models.CASCADE) token = models.CharField(max_length=64)
ser.py(序列化类...)
from rest_framework import serializers from app01.models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__'
app_auth.py(认证类)
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')
urls.py
from django.contrib import admin from django.urls import path from rest_framework import routers from app01 import views router = routers.SimpleRouter() # router = routers.DefaultRouter()#实例化路由更多,华而不实 router.register('book', views.BooksViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.LoginView.as_view()) ] urlpatterns += router.urls
settings.py注册drf组件和全局设置认证
""" Django settings for drf_day04work project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'yhwm7ckt=28=&^((o+4hq!5i%5@j!ktqgin292^75)c%phq$o^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', 'rest_framework' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'drf_day04work.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'drf_day04work.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' #全局认证 REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ["app01.app_auth.MyAuthentication", ] }