为什么我的 Django Rest Framework 端点会出现松散的右括号?
Why do I get loose closing brackets for my Django Rest Framework endpoint?
这是我对 http://localhost:8000/characters/api/users/1?format=json
的 JSON 回复
)]}',
{"id":1,"username":"admin","mage_by_user":[3],"mage_last_updated":"2015-02-11T16:13:16.229Z"}
注意第一行的)]}',
。
这是我的代码,它被调用来创建 JSON:
class UserSerializer(serializers.ModelSerializer):
mage_by_user = serializers.PrimaryKeyRelatedField(
many=True, queryset=Mage.objects.all())
mage_last_updated = serializers.ReadOnlyField(
source='mage_by_user.updated_date')
class Meta:
model = User
fields = ('id', 'username', 'mage_by_user', 'mage_last_updated',)
进一步测试:
- 我注意到页面的标题是
TypeError at <insert url here>
。
- 我所有的端点都会出现这种情况
如果我尝试访问 non-existent object(例如 userId=2),则为 DRF 呈现 'normally',例如:
{
详细信息:"Not found"
}
知道为什么会这样吗?
很抱歉没有提供更多帮助,但这看起来与 REST 框架完全无关。绝对不可能以那种方式呈现 JSON 响应。
也许您配置了自定义渲染器,它输出格式错误的响应,也许您有一些损坏的中间件插入了这些字符,也许这是客户端或您发出请求的任何环境中的问题,或者可能是什么原因否则与其中任何一个完全无关。
我首先会尝试尽可能缩小问题范围 - 从视图和序列化程序中移除所有复杂性并尝试在测试用例中复制行为。
很可能是您遗漏了某种意外的集成问题,或者忽略了一些明显的代码拼写错误。
这些字符是由 Djangular 中间件插入的AngularJsonVulnerabilityMiddleware
, to inject Json Vulnerability Protection
A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n"
. Angular will automatically strip the prefix before processing it as JSON.
不幸的是,这意味着它会破坏各种 JSON 观众。
这是我对 http://localhost:8000/characters/api/users/1?format=json
)]}',
{"id":1,"username":"admin","mage_by_user":[3],"mage_last_updated":"2015-02-11T16:13:16.229Z"}
注意第一行的)]}',
。
这是我的代码,它被调用来创建 JSON:
class UserSerializer(serializers.ModelSerializer):
mage_by_user = serializers.PrimaryKeyRelatedField(
many=True, queryset=Mage.objects.all())
mage_last_updated = serializers.ReadOnlyField(
source='mage_by_user.updated_date')
class Meta:
model = User
fields = ('id', 'username', 'mage_by_user', 'mage_last_updated',)
进一步测试:
- 我注意到页面的标题是
TypeError at <insert url here>
。 - 我所有的端点都会出现这种情况
如果我尝试访问 non-existent object(例如 userId=2),则为 DRF 呈现 'normally',例如:
{
详细信息:"Not found"
}
知道为什么会这样吗?
很抱歉没有提供更多帮助,但这看起来与 REST 框架完全无关。绝对不可能以那种方式呈现 JSON 响应。
也许您配置了自定义渲染器,它输出格式错误的响应,也许您有一些损坏的中间件插入了这些字符,也许这是客户端或您发出请求的任何环境中的问题,或者可能是什么原因否则与其中任何一个完全无关。
我首先会尝试尽可能缩小问题范围 - 从视图和序列化程序中移除所有复杂性并尝试在测试用例中复制行为。
很可能是您遗漏了某种意外的集成问题,或者忽略了一些明显的代码拼写错误。
这些字符是由 Djangular 中间件插入的AngularJsonVulnerabilityMiddleware
, to inject Json Vulnerability Protection
A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string
")]}',\n"
. Angular will automatically strip the prefix before processing it as JSON.
不幸的是,这意味着它会破坏各种 JSON 观众。