DRF中的BUG-××× is not json serializable

BUG现象:

TypeError: <property object at 0x7f2edd9e2228> 
is not JSON serializable

类型错误:×××对象不能被json化。

BUG产生的环境

python语言,Django框架,DRF设计风格

BUG原因:

Response的数据类型错误,没错,就是响应的数据类型出错。
错误代码:

# 情况1 捕获异常后返回响应
    except Exception as e:
         logger.error(e)
         return Response({'message': e})

# 情况2 直接返回字符串
    return Response('hello world')

解决BUG的方法

修改返回响应的类型,必须能够被序列化为json字符串

# 情况1
    except Exception as e:
         logger.error(e)
         return Response({'message': '%s' % e})

# 情况2
    return Response({'msg': 'hello world'})

猜你喜欢

转载自blog.csdn.net/MrNoboday/article/details/81210029