Monday, 7 August 2023

get client IP address from django request

 def get_client_ip(request):

    ip=None
    x_forwarded = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded:
        ip=x_forwarded.split(',')[0]
    elif not ip:
        ip = request.META.get('REMOTE_ADDR')
    else:
        ip = request.META.get('HTTP_X_REAL_IP')
    return ip

Sunday, 15 January 2023

Django rest framework Project tutorials part 5 modelviewset

In this tutorial, we are going study more about modelviewset

class ProfileViewset(viewsets.ModelViewSet):
    queryset =Profile.objects.all()
    serializer_class = ProfileSerilizer
    authentication_classes=[JWTTblUserAuthentication]
    permission_classes=[IsUser]
    allowed_methods = ('PUT','GET')



modelviewset

common policies

queryset 

serializer_class 

authentication_classes

permission_classes

allowed_methods 

rare policies

    renderer_classes 

    parser_classes 

    throttle_classes  

    content_negotiation_class  

    metadata_class 

    versioning_class 


common overriding function for modelviewset


POST

def create(self, request, *args, **kwargs):

GET

def list(self, request, *args, **kwargs):

PUT

def update(self, request, *args, **kwargs):

PATCH

def partial_update(self, request, *args, **kwargs):

DELETE

def destroy(self, request, *args, **kwargs):


def get_queryset(self):



def get_authenticators(self):


def get_permissions(self):


def as_view(cls, **initkwargs):


custom functions from action

from rest_framework.decorators import action

@action(methods=['post'],detail=False,authentication_classes=[JWTTblUserAuthentication])

def change_password(self,request):


detailed explanation:-

get_queryset

queryset =Profile.objects.all()

we can modify queryset from get_queryset overriding function

use case 

1.full record for user_type =staff or admin

2.customer can only manipulate his records

we only need to give the records with current user id matches the table record if user is customer or we can give full record if the user_type is staff or admin


    def get_queryset(self):
        queryset = Profile.objects.all()
        if self.request.user.id and self.request.user.usertype != 'customer':
            return queryset
        if self.request.user.id:
            return queryset.filter(id=self.request.user.id)


get_authenticators

use case

remove authetication if new record is creating else use autheticator from default

authentication_classes=[JWTTblUserAuthentication]

def get_authenticators(self):
        if self.request.method.lower()=='post':
            return []
        return super().get_authenticators()

if we are using method post then we dont need autheticator else we need JWTTblUserAuthentication

authetication

POST means we are using

def create(self, request, *args, **kwargs):


create

default method is POST

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


use cases

1.we can manipulate the data like changing different serializer

    def create(self, request, *args, **kwargs):
        self.serializer_class=ProfileSaveSerilizer
        return super().create(request, *args, **kwargs)

2. checking user 

3. changing response output if user is not customer, 

    def create(self, request, *args, **kwargs):
        self.serializer_class=ProfileSaveSerilizer
        if request.user.user_type=='customer':
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        return Response({},status=404)


destroy

default method is DELETE

def destroy(self, request, *args, **kwargs):

        return super().destroy(request, *args, **kwargs)


use case

we remove permission if user is destroying some others records

def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if request.user==instance.user:
            self.perform_destroy(instance)
            return Response(status=status.HTTP_204_NO_CONTENT)
        return Response(status=status.HTTP_403_FORBIDDEN)

 

list

default method is GET

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

use case do pagination number to 50 from default

change serilizer_class

filter queryset with record type is apple only

def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        queryset=queryset.filter(type='apple')
        self.pagination_class.page_size=50
        self.serializer_class=ApplelistSerializers
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


retrieve

default method is GET

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

use case

check current user is the owner of the record then show detail of that record change serizlizer to detailed one

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.user==request.user:
            self.serializer_class=ProfileDetailSerilizer
            serializer = self.get_serializer(instance)
            return Response(serializer.data)
        return Response()


get_permissions

def get_permissions(self):
        return super().get_permissions()

use case

if we need to put permission like create update delete for staff , and all others can only view the records

then we can override function like 

    def get_permissions(self):
        if self.action=='create' or self.action=='partial_update' or self.action=='update' or self.action=='destroy':
            self.permission_classes=[IsStaff]

        return super(ProfileViewset,self).get_permissions()




Jenkin pipeline for angular

 pipeline {

  agent any

    

  tools {nodejs "Node-12.10.0"}

   environment {

       NODE_OPTIONS = '--max-old-space-size=8192'                               //can be used in whole pipeline

   }

    

  stages {

      stage('echo') {

      steps {

        echo env.NODE_OPTIONS

      }

   

    }

        

    stage('Git') {

      steps {


         git branch: 'brnachname', credentialsId: 'xxxxxxxx-ccc7-49e2-a690-xxxxxxxxxxx', url: "git@****************"

        

      }

   

    }

     

    stage('install_npm') {

      steps {

          sh 'npm install firebase@4.8.0'

          sh 'npm install'

         

      }

    }  

    

            


     stage('prod_build') {

      steps {

        sh 'npm run ng build --prod --aot --output-hashing=all'

      }

    }

    stage('delete_projectname') {

      steps {

        sh 'sudo rm -rf /home/deploy/apps/projectname'

      }

    }

    stage('deploy_code_projectname') {

      steps {

        sh 'sudo cp -r ./dist/apps /home/deploy/apps/projectname'

      }

    }

    

  }

}