使用Django REST Framework时,cURL不显示JSON数据

时间:2018-02-26 16:20:41

标签: json django curl django-rest-framework

我对Django REST framework 2的教程有疑问。我使用cURL来测试我已经构建的序列化器。我还在数据库中添加了一些代码段数据。根据教程,我应该能够做到这一点:

    curl http://127.0.0.1:8000/snippets/

看到这个:

    [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]

我还希望看到Django服务器正在运行的HTTP响应代码为200。

如果我只是在浏览器中输入URI,我会在浏览器中看到JSON数据,在Django服务器控制台中看到200响应代码。但是当我从终端命令行运行curl命令时,我什么都看不到,我在Django控制台中得到了一个301 HTTP响应代码。在运行curl命令后,我做错了什么(或者不理解)阻止我在终端中看到JSON响应?

第二个问题是,是否可以从命令行查询API并在终端中查看JSON而不必在浏览器中查看它?

以下是所有代码:

    # snippets/models.py 
    class Snippet(models.Model):
        created = models.DateTimeField(auto_now_add=True)
        title = models.CharField(max_length=100, blank=True, default='')
        code = models.TextField()
        linenos = models.BooleanField(default=False)
        language = models.CharField(choices=LANGUAGE_CHOICES,
                                    default='python',
                                    max_length=100)
        style = models.CharField(choices=STYLE_CHOICES,
                                 default='friendly',
                                 max_length=100)

    # snippets/serializers.py
    class SnippetSerializer(serializers.ModelSerializer):
        class Meta:
            model = Snippet
            fields = ('id', 'title', 'code', 'linenos', 'language', 'style')

    # snippets/views.py
    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)

    @csrf_exempt
    def snippet_list(request):
        """
        List all code snippets, or create a new snippet.
        """
        if request.method == 'GET':
            snippets = Snippet.objects.all()
            serializer = SnippetSerializer(snippets, many=True)
            return JSONResponse(serializer.data)

    # snippets/urls.py
    urlpatterns = [
        url(r'^snippets/$', views.snippet_list),
    ]

0 个答案:

没有答案