Django Rest Framework:默认情况下以JSON格式输出到浏览器

时间:2017-08-04 05:40:28

标签: json django api django-rest-framework

我不想在网址中写?format=JSON。它应该默认返回JSON djangorestframework

3 个答案:

答案 0 :(得分:6)

settings.py需要添加以下设置..

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
    )
}

有关详细信息,请访问:http://www.django-rest-framework.org/api-guide/settings/

答案 1 :(得分:0)

rest-framework的可浏览API是 json 。没必要写

  

?format = JSON

网址中的

只是用户界面

如果你卷曲api根:

curl -I http://drf-demo.herokuapp.com/api/universities/
HTTP/1.1 200 OK
Connection: keep-alive
Server: gunicorn/19.4.5
Date: Fri, 04 Aug 2017 08:12:52 GMT
Transfer-Encoding: chunked
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Via: 1.1 vegur

答案 2 :(得分:0)

@Devasish为所有视图提供默认设置,但是您也可以设置用于单个视图或视图集的渲染器,如以下the DRF doco中的示例所示:

APIView class-based views.

from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView

class UserCountView(APIView):
    """
    A view that returns the count of active users in JSON.
    """
    renderer_classes = [JSONRenderer]

    def get(self, request, format=None):
        user_count = User.objects.filter(active=True).count()
        content = {'user_count': user_count}
        return Response(content)