Django-Rest-Framework

DRMF

Posted by indranil on Feb. 22, 2021, 2:53 p.m.

Django-Rest-FrameWork With Knox API Authenticate

Django is a Python-based free and open-source platfrom and 
django_rest_framework is a python module is used for access
database by third party app. Django Rest Framework was realised 
1st September 2014. This is the verry popular tool for pytho devlopers.

 

Django-rest-knox tokens are limited to one per user. This does not facilitate securely signing in from multiple devices, as the token is shared. CRUD Todo application with React, Redux, and Django (REST framework).  This time, we will implement user authentication, such as Login, for the application.

django rest framework django-rest-knox

In this python platfrom we need this module for use our project.
Simple way to Install any python module by pip.

pip install djangorestframework
pip install django-rest-knox

After setup your django project create app by name is api (You can choose ay type of name). Simple Create Your App By

python manage.py startapp api

After Setup On your Django Project settings.py file.

INSTALLED_APPS = [
    
    'rest_framework',
    'knox',
    'api.apps.ApiConfig',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'knox.auth.TokenAuthentication',
    ]
}

After setup on your settings.py file Follow Some Basic Step To Authenticated Your self.

django rest framework serializer

Serializers is allow to any type data converted to native 
Python datatypes that can then be easily rendered into JSON,
XML or other content types. Create serializers.py file on your api folder

#On serializers.py
# User Serializer
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email')

django rest api


#On views.py file

from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginAPI(KnoxLoginView):     permission_classes = (permissions.AllowAny,)     def post(self, request, format=None):         serializer = AuthTokenSerializer(data=request.data)         serializer.is_valid(raise_exception=True)         user = serializer.validated_data['user']         login(request, user)         return super(LoginAPI, self).post(request, format=None)

django authentication 

 Step4// urls.py
from knox import views as knox_views
from .views import LoginAPI
from django.urls import path

urlpatterns = [

   #django rest knox login
    path('login-api/', LoginAPI.as_view(), name='login'),
    #django rest knox logout
   
url(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'),
url(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall')


   ]



noimg Visit Link: digitalocean.com