url
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', views.Login.as_view()), # Book Table url(r'^books/$',views.BookHandle.as_view({ 'get':'list', 'post':'create' })), url(r'^books/(?P<pk>\d+)/',views.BookHandle.as_view({ 'get':'retrieve', 'put':'update', 'delete':'destroy' })), # 'get': 'retrieve', # 'put': 'update', # 'delete': 'destroy' # Author table url(r'^authors/$',views.AuthorHandle.as_view({ 'get':'list', 'post':'create' })), url(r'^authors/(?P<pk>\d+)/',views.AuthorHandle.as_view({ 'get':'retrieve', 'put':'update', 'delete':'destroy' })), # Publish Table url(r'^publishs/$',views.PublishHandle.as_view({ 'get':'list', 'post':'create' })), url(r'^publishs/(?P<pk>\d+)/',views.PublishHandle.as_view({ 'get':'retrieve', 'put':'update', 'delete':'destroy' })), ]
view
from app01.all_serializers import BookSerializer,AuthorSerializer,PublishSerializer from app01 import models from rest_framework.viewsets import ModelViewSet from rest_framework.response import Response from rest_framework.views import APIView import uuid # Create your views here. # Set landing token, to pave the way for certification class Login(APIView): # 200: 400 Success: Failure dic = {'code':None,'username':None,'msg':None,'token':None} def post(self,request): uname = request.data.get('username') upwd = request.data.get('password') user_obj = models.User.objects.filter(username=uname,password=upwd).first() if user_obj: random_str = uuid.uuid4() models.My_token.objects.update_or_create( defaults={'token':random_str}, user = user_obj ) self.dic['code'] = 200 self.dic['username'] = uname self.dic [ 'msg'] = 'login success' self.dic['token'] = random_str else: self.dic['code'] = 400 self.dic [ 'msg'] = 'Login Failed' return Response(self.dic) # Class certified components from rest_framework.exceptions import AuthenticationFailed # authentication fails, throw an exception from rest_framework.authentication import BaseAuthentication class UserInfo(BaseAuthentication): # This method can pass, but must be present def authenticate_header(self,request): pass # Authenticate a fixed method, and must have a parameter which is a new request object, do not believe, see Source def authenticate(self,request): When # query_params equivalent GET.get, get get request? Parameters carried back token = request.query_params.get('token') my_token_obj = models.My_token.objects.filter(token=token).first() if my_token_obj: # Request.user first parameter is returned User object table, the second parameter is the token request.auth return my_token_obj.user,token else: raise AuthenticationFailed ( 'authentication failure') # Class privilege components from rest_framework.permissions import BasePermission UserPermission class (BasePermission): message = 'VIP privileges to access the above' # This method must exist def has_permission(self,request,view): # Authentication component when returns two values, one is request.user, one is request.auth. if request.user.usertype >= 2 : return True return False # return True Class # access frequency components from rest_framework.throttling import BaseThrottle import time # Define a global dictionary to ensure that after the user access, the value of the dictionary there throttle_dic = {} class MyThrottle (BaseThrottle): mytime = 10 mycount = 5 # The current request time # Define methods method name and parameters can not be changed def allow_request(self, request, view): # Obtain login host id id = request.META.get('REMOTE_ADDR') # Define a class variable, because the wait method will be used self.now_time = time.time() # When the host did not request ID, please continue if id not in throttle_dic: throttle_dic[id] = [] # Define a class variable is used to define a list inside the dictionary, the method will be used in wait self.lis = throttle_dic[id] # When the host ID has a value, and the current time - the last time the list of saved time greater than the time interval 10s, removed the last save time, followed by cycle while self.lis and self.now_time - self.lis[-1] >= self.mytime : self.lis.pop() ID # when the host data is stored inside a frequency less than a defined number of times (5 times), the current time is stored in this list and can be accessed proof if len(self.lis) < self.mycount : self.lis.insert(0,self.now_time) return True Otherwise the number #, indicating that within a specified period of time, access exceeds the upper limit else: return False # This method must exist def wait(self): return self.lis[-1] + self.mytime - self.now_time
# Book table view function
class BookHandle (ModelViewSet):
# adding authentication component, the parameters can not be changed
authentication_classes = [the UserInfo,]
# add permissions component parameters can not be changed
permission_classes = [the UserPermission,]
# adding frequency components, parameters can not be changed
throttle_classes = [MyThrottle,]
QuerySet models.Book.objects.all = ()
# serialization component must be
serializer_class = BookSerializer
view of function table #
class AuthorHandle (ModelViewSet):
# adding authentication component, the parameters can not be changed
authentication_classes = [UserInfo ,]
# permissions added components, parameters can not be changed
permission_classes = [the UserPermission,]
# adding frequency components, parameters can not be changed
throttle_classes = [MyThrottle,]
QuerySet models.Author.objects.all = ()
# serialization component, must be
= AuthorSerializer serializer_class
# Press table serialization component
class PublishHandle (ModelViewSet):
# adding authentication component, the parameters can not be changed
authentication_classes = [the UserInfo,]
# permissions added components, parameters can not be changed
permission_classes = [the UserPermission,]
# adding frequency components, parameter can not be changed
throttle_classes = [MyThrottle,]
QuerySet models.Publish.objects.all = ()
# serialization component must be
serializer_class = PublishSerializer
all_serializers
from rest_framework import serializers from app01 import models Table # Book serialization component class BookSerializer(serializers.ModelSerializer): class Meta: model = models.Book fields = '__all__' # Many-field (not the same name with the field name) parameter source, read_only these two parameters have publish_name = serializers.CharField(max_length=32,source='publish.name',read_only=True) #-Many field (not the same name with the field name) author_name = serializers.SerializerMethodField() def get_author_name(self,obj): lis = [] author_obj_list = obj.authors.all() for author_obj in author_obj_list: dic = {} dic['name'] = author_obj.name lis.append(dic) return lis # Author table serialization component class AuthorSerializer(serializers.ModelSerializer): class Meta: model = models.Author fields = '__all__' Table # Publish serialization component class PublishSerializer(serializers.ModelSerializer): class Meta: model = models.Publish fields = '__all__'
models
from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) age=models.IntegerField() class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday=models.DateField() telephone=models.BigIntegerField() addr=models.CharField( max_length=64) class Publish(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) city=models.CharField( max_length=32) email=models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField( max_length=32) # publishDate=models.DateField() price=models.DecimalField(max_digits=5,decimal_places=2) publish = models.ForeignKey (to = "Publish", to_field = "nid", on_delete = models.CASCADE) # many to one table to Publish authors = models.ManyToManyField (to = 'Author',) # Author table to-many class User(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=32) my_type = ((1,'IP'),(2,'VIP'),(3,'SVIP')) usertype = models.IntegerField(choices=my_type,default=1) class My_token(models.Model): token = models.CharField(max_length=32) user = models.OneToOneField('User')