zoukankan      html  css  js  c++  java
  • restframework 自定义返回响应格式

    代码实现

    只需要继承rest_framework.responseResponse,重写self.data即可

    from rest_framework.response import Response
    
    
    class MyResponse(Response):
        def __init__(self, code=10000, msg="Success", data="", status=None,
                     template_name=None, headers=None,
                     exception=False, content_type=None):
            super(MyResponse, self).__init__(data, status, template_name, headers,
                                             exception, content_type)
    
            self.data = {"code": code, "msg": msg, "data": data}
    

    在视图中调用

    # 自定义的响应返回格式类
    from libs.success import MyResponse
    
    
    class Login(APIView):
        authentication_classes = []
    
        def post(self, request):
            username = request.data.get('username')
            password = request.data.get('password')
            user = User.objects.filter(phone=username).first()
            if user and user.check_pwd(password):
                r_dict = {'token': create_token({'user_id': user.id})}
                add_user.delay(username)
    
                con = get_redis_connection("default")
                con.set('token', create_token({'user_id': user.id}), 60)
                return MyResponse(data=r_dict)
            # 通过传入参数比如http状态码(status=301)
            return MyResponse(code=40000, msg="账号或密码错误", data='' status=301)
    
    

    正常参数

    异常参数

  • 相关阅读:
    Vue
    Vue
    Vue
    服务器上部署django项目流程?
    Git 命令
    git命令?
    消息队列中间件??
    简述COOKIE和SESSION的区别与联系?
    什么是restful API?
    Django、Flask、Tornado的区别?
  • 原文地址:https://www.cnblogs.com/se7enjean/p/13714267.html
Copyright © 2011-2022 走看看