Using djangorestframework

Time:2021-7-23

catalog:

1.1 basic use of djangorestframeworkBack to top

1. Review the basic use of CBV

from django.contrib import admin
from django.urls import path,re_path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'users/',include(('users.urls', 'users'), namespace='users'))
]

urls.py

from django.contrib import admin
from django.urls import path,re_path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'users/',include(('users.urls', 'users'), namespace='users'))
]

users/urls.py

import json
from django.shortcuts import render,HttpResponse
from django.views import View

class HomeView(View):

    def dispatch(self, request, *args, **kwargs):
        return super(HomeView, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return HttpResponse('get')

    def post(self, request):
        return HttpResponse('post')

users/views.py

2. Install djangorestframework

pip install djangorestframework==3.9.2
pip install markdown==3.0.1                  # Markdown support for the browsable API.
pip install django-filter==2.1.0             # Filtering support

3. Basic use of djangorestframework

from django.contrib import admin
from django.urls import path,re_path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'users/',include(('users.urls', 'users'), namespace='users'))
]

urls.py

from django.urls import path,re_path,include
from users import views

urlpatterns = [
    re_path(r'info', views.UserInfoViewSet.as_view(), name='user'),
]

users/urls.py

from rest_framework.views import APIView
from django.http import JsonResponse

class UserInfoViewSet(APIView):
    def __init__(self):
        super(UserInfoViewSet, self).__init__()

    def get(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'response data'
        }
        return JsonResponse(result, status=200)

    def post(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'response data'
        }
        return JsonResponse(result, status=200)

users/views.py

1.2 DRF authentication & authority moduleBack to top

1. Authentication basic usage

class UserInfoViewSet(APIView):
    authentication_ Classes = [authentication. Isauthenticated,] # user authentication module
    permission_ Classes = (authentication. Isowneroreadonly,) # user authorization module

from django.contrib import admin
from django.urls import path,re_path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'users/',include(('users.urls', 'users'), namespace='users'))
]

urls.py

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.urls import path,re_path,include
from users import views

urlpatterns = [
    re_path(r'info', views.UserInfoViewSet.as_view(), name='user'),
]

users/urls.py

from rest_framework.views import APIView
from django.http import JsonResponse
from common.auth import authentication

class UserInfoViewSet(APIView):
    authentication_classes = [authentication.IsAuthenticated,]
    permission_classes = (authentication.IsOwnerOrReadOnly,)

    def __init__(self):
        super(UserInfoViewSet, self).__init__()

    def get(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'response data'
        }
        return JsonResponse(result, status=200)

    def post(self, request, *args, **kwargs):
        result = {
            'status': True,
            'data': 'response data'
        }
        return JsonResponse(result, status=200)

users/views.py

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from rest_framework import authentication
from rest_framework import exceptions
from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_permission(self, request, view):
        If false: # permission verification will not be performed here
            Raise exceptions. ParseError ('You do not have permission to operate ')
        return True

class IsAuthenticated(authentication.BaseAuthentication):
    def authenticate(self, request):
        auth = request.META.get('HTTP_ Authorization ', none) # get authorization in header
        if auth is None:
            raise exceptions.NotAuthenticated()

        '"'Here should be the logic of verifying whether the token is legal'"
        # token = Token.objects.filter(key=auth)
        # try:
        #     request.user = token[0].user
        # except IndexError:
        #     raise exceptions.NotAuthenticated('Invalid input Authenticated')
        return (request, None)

    def authenticate_header(self, request):
        msg = 'Invalid token.Please get token first'
        return exceptions.NotAuthenticated(msg)

common\auth\authentication.py

2. Test interface

       

1.3 djangorestframework serializationBack to top

               

     

1. Option parameter ''
name = serializers.CharField(min_length=3,max_length=20)
max_ Length # maximum length
min_ Lenght # minimum length
allow_ Is blank allowed to be empty
max_ Value # maximum
min_ Value # min


2. General parameters
gp = serializers.SerializerMethodField(read_only=True) 
read_ Only # indicates that the field is only used for serialization output, and the default is false
write_ Only # indicates that the field is only used for deserializing input, and the default is false
Required # indicates that the field must be entered during deserialization. The default value is true
Default # the default value used when deserializing
allow_ Null # indicates whether the field is allowed to pass in none. The default is false
Validators # the validator used by this field
Label # is used to display the field name of API page in HTML
help_ Text # is used to display the field help prompt information when the API page is displayed in HTML
error_ Messages # contains a dictionary of error numbers and error messages

Serialize common field parameters

1. Serialization use

INSTALLED_APPS = [

    'rest_framework',
    'users',
]

settings.pySign up for app

from django.contrib import admin
from django.urls import path,re_path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'users/',include(('users.urls', 'users'), namespace='users'))
]

Urls.py defines the total route

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.urls import path,re_path
from users import views

urlpatterns = [
    re_path(r'^info/$', views.UserInfoViewSet.as_view(), name='userinfo'),
]

users/urls.py

from django.db import models

class UserInfo(models.Model):
    name = models.CharField(max_length=64,unique=True)
    ut = models.ForeignKey(to='UserType', on_delete=models.CASCADE)
    gp = models.ManyToManyField(to='UserGroup')

    def __str__(self):
        return self.name

class UserType(models.Model):
    type_name = models.CharField(max_length=64,unique=True)

    def __str__(self):
        return self.type_name

class UserGroup(models.Model):
    group = models.CharField(max_length=64)

    def __str__(self):
        return self.group

users/models.py

from rest_framework.views import APIView
from rest_framework.views import Response
import json

from users import serializers
from users import models as users_model

class UserInfoViewSet(APIView):
    #Query user information
    def get(self, request, *args, **kwargs):
        #One to many and many to many queries have the same syntax
        obj = users_model.UserInfo.objects.all()
        Ser = serializers. Userinfoserializer (instance = obj, many = true) # associate multiple data
        #Ser = serializers. Userinfoserializer (instance = obj [0]) associated data
        return Response(ser.data, status=200)

    #Create user
    '' create user '' '
    def post(self,request):
        ser = serializers.UserInfoSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(data=ser.data, status=201)
        return Response(data=ser.errors,status=400)

    #Update user information
    def put(self, request):
        pk = request.data.get('pk')
        userinfo = users_model.UserInfo.objects.get(id = pk)
        #Create a serialized object and pass the data to be deserialized to the data construction parameter for verification
        ser = serializers.UserInfoSerializer(userinfo,data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(data=ser.data, status=201)
        return Response(data=ser.errors,status=400)

users/views.py

from rest_framework import serializers
from users.models import UserInfo


class UserInfoSerializer(serializers.Serializer):
    name = serializers.CharField(min_ length=3,max_ Length = 20) # display common fields
    ut_ id = serializers.IntegerField(write_ Only = true) # foreign key constraint, the associated field should be defined
    ut = serializers.CharField(source='ut.type_ Name ', required = false) # displays the one to many field name
    gp = serializers.SerializerMethodField(read_ Only = true) # custom display (display many to many)
    XXX = serializers. Charfield (source ='name ', required = false) # you can also customize the display field name

    "'primarykeyrelatedfield and stringrelatedfield: you can use one to many and many to many association objects to serialize ''"
    # gp = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    # gp = serializers.StringRelatedField(read_only=True,many=True)

    class Meta:
        model = UserInfo

    #Custom display many to many fields
    def get_gp(self,row):
        '''row: it is the object of the userinfo table that is passed
        gp_ obj_ List = row. GP. All (). Values ('id ','group') #
        return gp_obj_list

    #Define creation syntax
    def create(self, validated_data):
        return UserInfo.objects.create(**validated_data)

    #Define update method
    def update(self, instance, validated_data):
        if validated_data.get('name'):
            instance.name = validated_data['name']
        if validated_data.get('ut_id'):
            instance.ut_id = validated_data['ut_id']
        instance.save()
        return instance

    #Define the method of single field validation
    def validate_name(self, value):
        if value == 'root':
            Raise serializers. Validationerror ('cannot create root administrator account ')
        return value

    #Define multi field validation methods
    def validate(self, attrs):
        if attrs['name'] == 'admin':
            Raise serializers. Validationerror ('admin user cannot be created ')
        return attrs


#One to many serialization (reverse lookup)
class UserTypeSerializer(serializers.Serializer):
    type_name = serializers.CharField()
    #Method 1 one to many association object serialization: this field will be serialized as the primary key of the association object
    userinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    #Method 2 one to many association object serialization: this field will be serialized as the string representation of the association object (i.e__ str__ Method's return value)
    # userinfo_set = serializers.StringRelatedField(read_only=True,many=True)
    #Method 3 one to many associated object serialization: use the serializer of the associated object
    # userinfo_set = UserInfoSerializer(many=True)


#Many to many serialization (reverse)
class UserGroupSerializer(serializers.Serializer):
    group = serializers.CharField()
    #Method 1 one to many association object serialization: this field will be serialized as the primary key of the association object
    # userinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    #Method 2 one to many association object serialization: this field will be serialized as the string representation of the association object (i.e__ str__ Method's return value)
    # userinfo_set = serializers.StringRelatedField(read_only=True,many=True)
    #Method 3 one to many associated object serialization: use the serializer of the associated object
    # userinfo_set = UserInfoSerializer(many=True)

users/serializers.py

2. Serialization(serializers.Serializer

1) Serialization (forward lookup)

from rest_framework import serializers
from users.models import UserInfo

class UserInfoSerializer(serializers.Serializer):
    name = serializers.CharField(min_ length=3,max_ Length = 20) # display common fields
    ut = serializers.CharField(source='ut.type_ Name ', required = false) # displays the one to many field name
    gp = serializers.SerializerMethodField(read_ Only = true) # custom display (display many to many)
    XXX = serializers. Charfield (source ='name ', required = false) # you can also customize the display field name
    ut_ id = serializers.IntegerField(write_ Only = true) # one to many association field definition (foreign key constraint)

    "'primarykeyrelatedfield and stringrelatedfield: you can use one to many and many to many association objects to serialize ''"
    # gp = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    # gp = serializers.StringRelatedField(read_only=True,many=True)

    class Meta:
        model = UserInfo

    #Custom display many to many fields
    def get_gp(self,row):
        '''row: it is the object of the userinfo table that is passed
        gp_ obj_ List = row. GP. All (). Values ('id ','group') #
        return gp_obj_list

2) Serialization (reverse lookup)

'''one to many serialization (reverse lookup)' '
class UserTypeSerializer(serializers.Serializer):
    type_name = serializers.CharField()
    #Method 1 one to many association object serialization: this field will be serialized as the primary key of the association object
    userinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    #Method 2 one to many association object serialization: this field will be serialized as the string representation of the association object (i.e__ str__ Method's return value)
    # userinfo_set = serializers.StringRelatedField(read_only=True,many=True)
    #Method 3 one to many associated object serialization: use the serializer of the associated object
    # userinfo_set = UserInfoSerializer(many=True)

3) Using serialization in view functions

class UserInfoViewSet(APIView):
    def get(self, request, *args, **kwargs):
        #One to many and many to many queries have the same syntax
        obj = users_model.UserInfo.objects.all()
        Ser = serializers. Userinfoserializer (instance = obj, many = true) # associate multiple data
        #Ser = serializers. Userinfoserializer (instance = obj [0]) associated data
        return Response(ser.data, status=200)

3. Deserialization

1) Using deserialization to save data

'' create user '' '
def post(self,request):
    ser = serializers.UserInfoSerializer(data=request.data)
    if ser.is_valid():
        ser.save()
        return Response(data=ser.data, status=201)
    return Response(data=ser.errors,status=400)

2) Deserialization defines the creation and update methods

#Define creation syntax
    def create(self, validated_data):
        return UserInfo.objects.create(**validated_data)

    #Define update method
    def update(self, instance, validated_data):
        if validated_data.get('name'):
            instance.name = validated_data['name']
        if validated_data.get('ut_id'):
            instance.ut_id = validated_data['ut_id']
        instance.save()
        return instance

    #Define the method of single field validation
    def validate_name(self, value):
        if value == 'root':
            Raise serializers. Validationerror ('cannot create root administrator account ')
        return value

    #Define multi field validation methods
    def validate(self, attrs):
        if attrs['name'] == 'admin':
            Raise serializers. Validationerror ('admin user cannot be created ')
        return attrs

4. Examples of serialization(serializers.ModelSerializer

1. The essence of modelserializer is to inherit the serializer class and add some functions

2. Modelserializer can be used       fields = ‘__ all__’       Define the fields to display

'''users/serializers/userinfo_serializers.py'''

from rest_framework import serializers
from users.models import UserInfo

class UserInfoSerializer(serializers.ModelSerializer):
    #Name = serializers. Charfield() # display common fields
    ut = serializers.CharField(source='ut.type_ Show one to many fields
    GP = serializers. Serializermethodfield() # custom display (show many to many)
    XXX = serializers. Charfield (source ='name ') # you can also customize the display field name

    class Meta:
        model = UserInfo
        # fields = "__all__"
        Fields = ["name",'ut ',' GP ',' xxx '] # define which fields to display

    def get_gp(self,row):
        '''row: it is the object of the userinfo table that is passed
        gp_ obj_ List = row. GP. All() # get all groups of the user
        ret = []
        for item in gp_obj_list:
            ret.append({'id':item.id,'gp':item.group})
        return ret

Serializers.modelserializer

5. Data validation using serializers.modelserializer

from rest_framework.views import APIView
from users.serializers.userinfo_serializers import UserInfoSerializer
from users.models import UserInfo

class UserInfoViewSet(APIView):
    def get(self, request, *args, **kwargs):
        obj = UserInfo.objects.all()
        ser = UserInfoSerializer(instance=obj,many=True)
        ret = json.dumps(ser.data,ensure_ascii=False)
        return HttpResponse(ret)

    def post(self, request, *args, **kwargs):
        Ser = userinfoserializer (data = request. Data) # validation to validate the data sent by the request
        if ser.is_valid():
            print(ser.validated_ Data) # post request data dictionary
        else:
            Print (Ser. Errors) ා form validation error message
        return HttpResponse(json.dumps({'status':True}))

users/views.py

'''users/serializers/userinfo_serializers.py'''

from rest_framework import serializers
from django.core.exceptions import ValidationError
from users.models import UserInfo

class UserInfoSerializer(serializers.ModelSerializer):
    name = serializers.CharField(min_ length=10, error_ Messages = {required ':'The field is required'}) # display common fields
    ut = serializers.CharField(source='ut.type_ Name ', required = false) # displays one to many fields
    GP = serializers. Serializermethodfield (required = false) # custom display (display many to many)
    XXX = serializers. Charfield (source ='name ', required = false) # you can also customize the display field name

    class Meta:
        model = UserInfo
        # fields = "__all__"
        Fields = ["name",'ut ',' GP ',' xxx '] # define which fields to display

    #Local hook:
    def validate_ Name (self, value): # value is the value submitted by the name field
        If value. Startswitch ('sb '): # cannot start with sb
            Raise validationerror ('cannot start with sb ')
        else:
            return value

    #Global hook found
    Def validate (self, value): # value is the dictionary of all data that pass validation
        name = value.get('name')
        if False:
            Raise validationerror ('exception thrown by global hook ')
        return value

users/serializers/userinfo_serializers.py

'''1、ser.is_valid()'''
#Verify whether the data in the post request is legal

'"'2. Global check hook'"
Def validate (self, value): # value is the dictionary of all data that pass validation

3. Local hook
def validate_ Name (self, value): # value is the value submitted by the name field

1.4 djangorestframework pagingBack to top

1. Basic syntax in pagination

1. Instantiate a Paginator object
paginator = Paginator(objs, page_ Size) # Paginator object

2. Get the total number of pages
total_ Count = Paginator. Count # total quantity
total = paginator.num_ Pages total pages

'"'3. Use objs object to get the specified number of pages'"
objs = paginator.page(page)

4. Serializing the paging data
Serializer = serializer (objs, many = true) # serialization operation

2. Examples of paging module

#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf import settings
from rest_framework import status
from django.core.paginator import EmptyPage, Paginator, PageNotAnInteger
from rest_framework.views import Response


def Paginators(objs, request, Serializer):
    """
    Objs: entity object, queryset
    Request: request object
    Serializer: the class corresponding to the entity object
    page_ Size: how many pieces of data are displayed on each page
    Page: which page of data is displayed
    total_ Count: how many pieces of data are there in total
    Total: total pages
    """
    try:
        page_size = int(request.GET.get('page_size', settings.REST_FRAMEWORK['PAGE_SIZE']))
        page = int(request.GET.get('page', 1))
    except (TypeError, ValueError):
        return Response(status=400)

    paginator = Paginator(objs, page_ Size) # Paginator object
    total_count = paginator.count
    total = paginator.num_ Pages total pages
    try:
        objs = paginator.page(page)
    except PageNotAnInteger:
        objs = paginator.page(1)
    except EmptyPage:
        objs = paginator.page(paginator.num_pages)
    Serializer = serializer (objs, many = true) # serialization operation
    return Response(
        data={
            'detail': serializer.data,
            'page': page,
            'page_size': page_size,
            'total': total,
            'total_count': total_count
        }
    )

common/utils/api_ Paginator.py custom paging module

#Pagination
REST_FRAMEWORK = {
    #Global paging
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    #Close API root page display
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'UNICODE_JSON': False,
    #Custom exception handling
    'EXCEPTION_HANDLER': (
            'common.utils.custom_exception_handler'
        ),
    'PAGE_SIZE': 10
}

settings.py

'''users/serializers/userinfo_serializers.py'''

from rest_framework import serializers
from users.models import UserInfo

class UserInfoSerializer(serializers.Serializer):
    Name = serializers. Charfield() # display common fields
    ut = serializers.CharField(source='ut.type_ Show one to many fields
    GP = serializers. Serializermethodfield() # custom display (show many to many)
    XXX = serializers. Charfield (source ='name ') # you can also customize the display field name

    class Meta:
        model = UserInfo

    def get_gp(self,row):
        '''row: it is the object of the userinfo table that is passed
        gp_ obj_ List = row. GP. All() # get all groups of the user
        ret = []
        for item in gp_obj_list:
            ret.append({'id':item.id,'gp':item.group})
        return ret

users/serializers/userinfo_serializer.py

''' users/views.py'''

from rest_framework.views import APIView
from rest_framework.views import Response
from users.serializers.userinfo_serializers import UserInfoSerializer
from users.models import UserInfo
from common.utils.api_paginator import Paginators

class UserInfoViewSet(APIView):
    queryset = UserInfo.objects.all().order_by('id')
    serializer_class = UserInfoSerializer

    def get(self, request, *args, **kwargs):
        self.queryset = self.queryset.all()
        ret = Paginators(self.queryset, request, self.serializer_class)
        Print (json.dumps (ret.data)) # ret.data returns the final query JSON data
        return Response(ret.data)

# http://127.0.0.1:8000/users/info/?page_size=1
'''
{
    "detail": [
        {
            "name": "zhangsan",
            "Ut": students,
            "gp": [
                {
                    "id": 1,
                    "gp": "group01"
                },
                {
                    "id": 2,
                    "gp": "group02"
                }
            ],
            "xxx": "zhangsan"
        }
    ],
    "page": 1,
    "page_size": 1,
    "total": 3,
    "total_count": 3
}
'''

users/views.py

1.5 JWT: use djangorest framework JWT module for user authenticationBack to top

     Installation: pip install djangorestframework-jwt

     Add application:python manage.py startapp users

     Official website:https://jpadilla.github.io/django-rest-framework-jwt/

1. JWT configuration and use

###########1. In installed_ Add 'rest' to apps_ framework.authtoken', #################
INSTALLED_APPS = [
    '''
    'rest_framework.authtoken',  # 
    '''
]

###################2. Configure JWT verification######################
REST_FRAMEWORK = {
    #Identity authentication
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

import datetime

JWT_AUTH = {
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
    'JWT_RESPONSE_PAYLOAD_HANDLER':
        'users.views.jwt_ response_ payload_ Handler ', # re login return function
}
AUTH_ USER_ Model = users. User 'ා specifies to use the model user in the users app for verification

Settings.py configure JWT

from django.contrib import admin
from django.urls import path,re_path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'users/',include(('users.urls','users'),namespace='users'))
]

urls.py

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.urls import path,re_path,include
from users import views
from rest_ framework_ jwt.views import obtain_ jwt_ Token ා after verifying the password, the token is returned

urlpatterns = [
    path('v1/register/', views.RegisterView.as_ View(), name ='register '), # register user
    path('v1/login/', obtain_ jwt_ Token, name ='login '), # the token is returned after the user logs in
    path('v1/list/', views.UserList.as_ View(), name '='register'), # the test needs to carry a token to access
]

users/urls.py

from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
    username = models.CharField(max_length=64, unique=True)
    password = models.CharField(max_length=255)
    phone = models.CharField(max_length=64)
    token = models.CharField(max_length=255)

users/models.pyAdd user table for user authentication

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from rest_framework_jwt.settings import api_settings
from rest_framework import serializers
from users.models import User

class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()
    phone = serializers.CharField()
    token = serializers.CharField(read_only=True)

    def create(self, data):
        user = User.objects.create(**data)
        user.set_password(data.get('password'))
        user.save()
        #Supplementary generation of token to record login status
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user

users/serializers.pyUsing the Create method of serializer to create token

from django.shortcuts import render
import json
from rest_framework.views import APIView
from rest_framework.views import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from users.serializers import UserSerializer


#User registration
class RegisterView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)


#Re login return function
def jwt_response_payload_handler(token, user=None, request=None):
    '''
    : param token: token value generated by JWT
    : param user: user object
    : param request: request
    '''
    return {
        'token': token,
        'user': user.username,
        'userid': user.id
    }


#The test must carry a token to access the interface
class UserList(APIView):
    permission_ Classes = [isauthenticated] # add permissions to the interface
    authentication_classes = [JSONWebTokenAuthentication]

    def get(self,request, *args, **kwargs):
        print(request.META.get('HTTP_AUTHORIZATION', None))
        return Response({'name':'zhangsan'})
    def post(self,request, *args, **kwargs):
        return Response({'name':'zhangsan'})

users/views.py

#1. Specify the allowed hosts, otherwise pass the http://jack.com:8888/index/  Unable to access Jack_ Django program
ALLOWED_HOSTS = ['*']

#2. Register the corsheaders in the app
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'app01',
]

#3. Add the following two items to the middleware
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

#4. Configure parameters in Django CORS headers
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
# CORS_ORIGIN_WHITELIST = (
#     '*',
# )

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

settings.py The front and back end are separately configured with CORS

                

      

#Get user information from rest through user token_ framework_ jwt.utils import jwt_ decode_ handler
toke_user = jwt_decode_handler(token)
# {'user_id': 2, 'username': 'lisi', 'exp': 1561504444, 'email': ''}

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]