我按照Django Rest框架
官方文档中的“编写常规Django View ...”并得到了这样的代码:
#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/页面时,他或她会看到一个漂亮的 json 格式数据 [{"a":"1","b":"2"},{"c":"3 ","d":"4"}]
。但是,我如何获取(代码?)api 格式的数据,或者检查用户是否请求 ?format=api
然后以 api 格式方式呈现,如果没有,则以 json 格式呈现。我所说的 api 格式的数据是指这种 view
最佳答案
尝试使用 @api_view() 装饰器,如所述 here 。并确保使用内置的 Response 而不是 JSONResponse。
您的 View 应如下所示:
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
关于python - 如何从 Django 获取 api 格式响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29047312/