如何重写APIView的`post`方法?

时间:2017-11-29 11:42:26

标签: python django django-rest-framework

如何重写APIView的post方法?

我尝试重写post方法,如bellow,但似乎错过了一些东西。

class CloudServerShutdownAPIView(APIView):
    """
    shut down the server
    """
    serializer_class = CloudServerShutdownSerializer
    def post(self, request):
        cloudserver_id = request.data.pop("cloudserver_id")
        try:
            openstackServerShutdown(server_or_id=cloudserver_id)
        except Exception as e:
            return Response(data="shut down server fail", status=HTTP_404_NOT_FOUND, exception=e)

如何正确重写post方法?

修改

回溯如下:

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework/views.py", line 491, in dispatch
    self.response = self.finalize_response(request, response, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework/views.py", line 406, in finalize_response
    % type(response)
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

1 个答案:

答案 0 :(得分:0)

class CloudServerShutdownAPIView(APIView):
    """
    shut down the server
    """
    serializer_class = CloudServerShutdownSerializer
    def post(self, request):
        cloudserver_id = request.data.pop("cloudserver_id")
        try:
            openstackServerShutdown(server_or_id=cloudserver_id)
            return Response(data="shut down server successful", status=HTTP_200_OK)
        except Exception as e:
            return Response(data="shut down server fail", status=HTTP_404_NOT_FOUND, exception=e)

这是因为您在成功关闭期间没有发送任何响应