【问题标题】:Removing additional double quotes in django rest response在 django rest 响应中删除额外的双引号
【发布时间】:2021-02-12 23:54:52
【问题描述】:

我是 Django REST 框架的新手,我尝试创建一个视图

class TestView(APIView):

    def get(self, request, *args, **kwargs):
        return Response("Hello world")

当我在 python 中使用 curl 或请求模块发送请求时:

curl -X GET localhost:8000/test/

我得到“Hello world”作为响应,我真正需要的是没有额外双引号的 Hello world 字符串。 我尝试了不同的 content_types,但到目前为止它们都没有奏效。 我怎样才能摆脱双引号?

【问题讨论】:

  • 返回 Django HttpResponse 而不是 rest_framework Response。 rest_framework Response 会将字符串转换为 JSON 并添加引号
  • @IainShelvington 有什么办法可以改变这种行为吗?
  • @Maryam 您可能应该使用自定义渲染器。看看django-rest-framework.org/api-guide/renderers

标签: python django api django-rest-framework


【解决方案1】:

正如 Iain 所说,使用 HttpResponse 而不是 Response

from django.http import HttpResponse

class TestView(APIView):
    def get(self, request, *args, **kwargs):
        return HttpResponse("Hello world")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    相关资源
    最近更新 更多