首页 > 解决方案 > 在 Python 发出 post 请求时如何调用函数?

问题描述

我使用 django rest 框架进行编程。由于 DRF 是 CRUD 自动的,因此我创建了一个如下所示的视图。

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

顺便说一句,我想在发出 post 请求时调用以下函数。

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)

我应该怎么办?

标签: pythondjangodjango-rest-framework

解决方案


尝试这个。发布请求后调用您的函数。

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)

推荐阅读