在DRF中实现自定义Response类

时间:2015-09-25 04:57:38

标签: python django api rest django-rest-framework

my views.py:

class OptiResponse(Response):
    def __init__(self, token=None, code=None, headers=None):
        if code==0:
            if token:
                data = {
                    "status":{
                        "code": 0,
                        "error_message": "" 
                    },
                    "data":{
                        "token":token,
                    }
                }   
            data = {
                    "status":{
                        "code": 0,
                        "error_message": "" 
                    },
                    "data":{

                    }
            }
        data = {
                "status":{
                    "code": 1,
                    "error_message": "" 
                },
                "data":{

            }
        }

        self.token=token
        self.data = data

        if headers:
            for name, value in six.iteritems(headers):
                self[name] = value

    @property
    def rendered_content(self):
        return ret

    @property
    def status_text(self):
        return responses.get(self.status_code, '')

    def __getstate__(self):
        return state


class LoginView(generics.CreateAPIView):
    serializer_class = serializers.LoginSerializer

    """Authenticate and Login a user."""
    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            email = serializer.data['email']
            password = serializer.data['password']
            remember = serializer.data['remember_me']

            user = authenticate(email=email, password=password)

            if user:
                if user.is_active:
                    if remember:
                        request.session.set_expiry(120)

                    login(request, user)
                    token = Token.objects.get(user=user)
                    return OptiResponse(0, token.key)

以上是我当前应用视图的快照。我正在研究DRF API,我想自定义DRF的Response类。我想用两个参数调用响应,如上面的'Reponse(code, token)',其中rest API输出的格式应符合下面显示的代码值:

                 {
                    "status":{
                        "code": 0, #either 0 in success or 1 in error.
                        "error_message": "" 
                    },
                    "data":{

                    }
                 }

是否可以通过在我自己的类中继承'Response'类来实现。可能是我以错误的方式做这件事。请建议我可能的解决方案。

谢谢!提前。

1 个答案:

答案 0 :(得分:0)

何保罗, 如果您想创建自定义响应,您应该:

  • 不要使用父SimpleTemplateResponse编写您的类 响应
  • 并注意content_type o fyour reponse
class MyCustomResponse(SimpleTemplateResponse):
    def __init__(self,code=None,token=None):


        super(Response, self).__init__(None, status=None)


        """
          PUT YUOR DATA CODES HERE ....
        """


        self.token = token
        self.code = code

        if headers:
            for name, value in six.iteritems(headers):
                self[name] = value

     @property
     def rendered_content(self):
         renderer = getattr(self, 'accepted_renderer', None)
         media_type = 'application/json'
         context = getattr(self, 'renderer_context', None)

         assert renderer, ".accepted_renderer not set on Response"
         assert media_type, ".accepted_media_type not set on Response"
         assert context, ".renderer_context not set on Response"
         context['response'] = self

         content_type = 'application/json'


         self['Content-Type'] = content_type

        ret = renderer.render(self.data, media_type, context)

         if not ret:
             del self['Content-Type']

         return ret