【问题标题】:how return json as text file in django rest framework如何在 django rest 框架中将 json 作为文本文件返回
【发布时间】:2018-04-02 01:26:12
【问题描述】:

这是一个非常幼稚的问题,这意味着我对 DRF 的工作原理不太了解,但仍然: 以包含 json 的文本文件形式从 DRF 获取响应的方式是什么?

我有一个 ListAPIView:

class MyModelJSONView(generics.ListAPIView):
   serializer_class = MySerializer
   queryset = MyModel.objects.all()

我想我应该以某种方式重写此ListAPIViewget 方法以获取文本文件(我假设通过将Content-Disposition 添加到响应中。但是如何?

【问题讨论】:

  • 问了一个类似的问题并回答了here
  • 您始终可以将 JSON 响应保存到文本文件中。

标签: json django django-rest-framework


【解决方案1】:
class MyModelJSONView(generics.ListAPIView):

    def get(self, request):

        filename = 'test.txt'
        queryset = MyModel.objects.all()
        serializer = MySerializer(queryset)
        response = HttpResponse(serializer.data, content_type='text/plain; charset=UTF-8')
        response['Content-Disposition'] = ('attachment; filename={0}'.format(filename))

        return response

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 2017-08-21
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多