如何从Django获取api格式响应

时间:2015-03-14 09:18:30

标签: python django rest django-rest-framework

我从Django Rest framework的官方文档中跟随“编写常规Django视图...”并得到了这样的代码:

#views.py file

#imports go here

class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

def items(request):
    output = [{"a":"1","b":"2"},{"c":"3","d":"4"}]
    return JSONResponse(output)

效果很好。当用户访问/ items / page时,他或她会看到一个看起来很漂亮的json格式数据[{"a":"1","b":"2"},{"c":"3","d":"4"}]。但是,如何获取(代码?)api-formated数据,或者检查用户是否请求?format=api然后以api格式呈现,如果没有,则以json格式呈现。通过api-formated数据我的意思是这种view

1 个答案:

答案 0 :(得分:1)

尝试使用here所述的@api_view()装饰器。并确保使用内置的Response而不是JSONResponse。

您的观点应该是这样的:

from rest_framework.decorators import api_view

...

@api_view()   
def items(request):
    output = [{"a":"1","b":"2"},{"c":"3","d":"4"}]
    return Response(output)    

在收到错误的情况下

Cannot apply DjangoModelPermissions on a view that does not have model or queryset property

从settings.py

中的其余框架权限设置中删除DjangoModelPermissions