How do I call a function when I make a post request at Python?

1.9k Views Asked by At

I programmed using the django rest framework. Since DRF is CRUD automatic, I created a view as shown below.

class PostViewSet(viewsets.ModelViewSet):
  permission_classes = [permissions.IsAuthenticatedOrReadOnly]
  serializer_class = PostSerializer
  queryset = AllfindPost.objects.all()

By the way, I would like to call the following functions when I make a post request.

def send_fcm_notification(ids, title, body):

    url = 'https://fcm.googleapis.com/fcm/send'

    headers = {
        'Authorization': 'key=',
        'Content-Type': 'application/json; UTF-8',
    }

    content = {
        'registration_ids': '',
        'notification': {
            'title': 'title',
            'body': 'body'
        }
    }

    requests.post(url, data=json.dumps(content), headers=headers)

What should I do?

1

There are 1 best solutions below

1
On BEST ANSWER

Try this. Call your function after post request.

def call_my_function():
    pass

class PostViewSet(viewsets.ModelViewSet):
  permission_classes = [permissions.IsAuthenticatedOrReadOnly]
  serializer_class = PostSerializer
  queryset = AllfindPost.objects.all() 

    """
    Create a model instance.
    """
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        #call your function Eg.
        call_my_function()
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)