为什么我的Django Rest Framework端点可以收到松散的关闭括号? [英] Why do I get loose closing brackets for my Django Rest Framework endpoint?

查看:107
本文介绍了为什么我的Django Rest Framework端点可以收到松散的关闭括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JSON响应 http:// localhost:8000 / characters / api / users / 1?format = json



pre> )]}',
{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在 & lt; insert url here>

  • 这一切都发生在我的所有端点

  • 如果我尝试访问不存在的对象(例如userId = 2),然后为DRF呈现正常,例如:



    {

    detail:没有找到

    }




b $ b

解决方案

这些字符由Djangular中间件 AngularJsonVulnerabilityMiddleware ,注入 Json漏洞保护


A JSON漏洞允许第三方网站在某些条件下将JSON资源URL转换为JSONP请求。为了解决这个问题,您的服务器可以使用以下字符串)]}',\\\
前缀所有JSON请求。角色将自动剥离前缀,然后将其处理为JSON。


不幸的是,这意味着它会破坏各种JSON观众。


Here's my JSON response for 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"}

Notice the )]}', on the first line.

Here is my code that gets called to create the 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',)


Further testing:

  • I've noticed the title of the page is TypeError at <insert url here>.
  • This happens with all of my endpoints
  • If I try to access a non-existent object (userId=2 for instance), then renders 'normally' for DRF, e.g:

    {
    detail: "Not found"
    }

Any idea why this would happen?

解决方案

Those characters are inserted by the Djangular middleware 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.

Unfortunately, it means it breaks various JSON viewers.

这篇关于为什么我的Django Rest Framework端点可以收到松散的关闭括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆