Exemplo n.º 1
0
    def check_json(self, instance=None, schema=None):
        """
        校验Json数据
        :param instance: 被校验数据
        :param schema: json格式模板 -> dict
        :return: None
        """

        self.init(instance=instance, schema=schema)

        try:
            validate(instance=instance, schema=self.json_schema)
        except exceptions.SchemaError as e:  # schema模式无效
            raise exception.myException400({
                "success": False,
                "msg": "{}".format(e.message)
            })
        except exceptions.ValidationError as e:  # JSON数据实例无效
            raise exception.myException400({
                "success":
                False,
                "msg":
                "{}:{}".format(e.relative_path.pop(), e.message)
            })
        except:
            raise exception.myException400({
                "success": False,
                "msg": "Json校验异常"
            })

        return None
Exemplo n.º 2
0
    def create(self, validated_data):
        data = self.context["request"].data
        blogid = eval(data.get("blogid",["-1"])[0]) # 获取文章id
        if blogid <= 0: # id 异常, 报错
            raise exception.myException400({
                "success": False,
                "msg": "保存失败,文章不存在",
                "results": "",
            })
        else: # id 正常
            article_list = models.Article.objects.filter(id=blogid) # 获取id对应的文章列表
            if not article_list.exists(): # 在数据库中能找不到这个id对应的文章
                raise exception.myException400({
                    "success": False,
                    "msg": "保存失败,文章不存在",
                    "results": "",
                })
            else: # 数据库中存在着篇文章
                file = data.get("file", None) # 获取前端传过来的图片数据流
                if not file: # 图片为空
                    raise exception.myException400({
                        "success": False,
                        "msg": "保存失败,后端没拿到图片",
                        "results": "",
                    })
                else: # 图片不为空
                    base64_data = FileBase.image_to_base64(file)
                    article_obj = article_list.first() # 获取文章对象
                    article_obj.image = base64_data # 更新图片
                    article_obj.save() # 保存实例

        return article_obj # 返回实例
Exemplo n.º 3
0
 def validation_error(self, serializer):
     """
     自定义序列化捕获异常函数
     :param serializer: 序列化后的对象
     :return: None
     """
     try:
         ret = serializer.is_valid(raise_exception=True) # 捕获异常
     except Exception as e:
         print("序列化异常处理函数,e:{}".format(e))
         dict_exception = e.__dict__.get("detail","")
         if "success" in dict_exception:
             self.msg_error = dict_exception["msg"]
         else:
             for i, v in dict_exception.items():
                 self.msg_detail = i
                 self.msg_error = v[0]
                 break # 只获取第一个异常结果
         raise exception.myException400({
             "success": False,
             "msg": "{}".format(self.msg_error), # 异常消息
             "results":{
                 "field":self.msg_detail, # 具体异常的字段
                 "detail":self.msg_error, # 异常消息
             }
         })
     return None
Exemplo n.º 4
0
 def check_field(self, instance=None, schema=None):
     if instance.keys() != schema.keys():
         raise exception.myException400({
             "success":
             False,
             "msg":
             "参数不符合要求,需要:[{}],获取的:[{}]".format(schema.keys(),
                                               instance.keys()),
             "results":
             "",
         })
Exemplo n.º 5
0
    def check_auth_base(self, username, password):
        """
        校验用户名和密码是否匹配
        :param username: 用户名
        :param password: 密码
        :return: bool
        """
        user = authenticate(username=username, password=password)
        if not user:
            raise exception.myException400({
                "success": False,
                "msg": "账号密码不匹配",
                "results": None,
            })

        return True
Exemplo n.º 6
0
    def create(self, validated_data):

        data = self.context["request"].data
        user = self.context["request"].user
        file = data.get("file", None)  # 获取前端传过来的图片数据流
        if not file:  # 图片为空
            raise exception.myException400({
                "success": False,
                "msg": "保存失败,后端没拿到图片",
                "results": "",
            })
        else:  # 图片不为空
            base64_data = FileBase.image_to_base64(file)
            user.avatar = base64_data  # 更新图片
            user.save()  # 保存实例

        return user
Exemplo n.º 7
0
    def get_object_base(self, model, field):
        """
        获取对象
        :param field: 字段
        :param model: 模型
        :return: instance
        """

        try:
            instance = get_object_or_404(model, username=field)

        except:
            raise exception.myException400({
                "success": False,
                "msg": "获取instance异常",
                "results": ""
            })

        return instance
    def update(self, instance, validated_data):
        """
        :param instance: 实例
        :param validated_data: Put携带的参数
        :return: instance
        """
        print(validated_data)
        state = validated_data.get("state",0)
        if state == 1: # 确认发布文章, 需要上传图片
            if not instance.image: # 图片为空
                raise exception.myException400({
                    "success": False,
                    "msg": "请上传图片",
                    "results": "",
                })
        instance.subtitle = validated_data.get("subtitle","")
        instance.tag = validated_data.get("tag","{}")
        instance.state = state
        instance.save()

        return instance