TypeError: Object of type 'HttpResponseRedirect' is not JSON serializable

TypeError: Object of type 'HttpResponseRedirect' is not JSON serializable

我正在尝试 运行 一个简单的应用程序,它从外部应用程序接收有效负载并进入 EntryLayerView。此视图调用 utils.py 中的方法,然后将有效负载重定向到另一个视图进行处理。但是,我一直看到这不是 Json 可序列化的错误。

Url.py

path(
        "api/v2/myapp/assessments",
        views.EntryLayerView.as_view(),
        name="myapp-assessments",
    ),
    path(
        "api/v2/myapp/startconversation",
        views.startconversation.as_view(),
        name="myapp-start-assessment",
    ),

Views.py 应用程序的入口点是 EntryLayerView

class EntryLayerView(generics.GenericAPIView):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        body = request.data
        response = get_endpoint(validated_body) #Don't worry about this line
        return Response(response, status=status.HTTP_200_OK)


class startconversation(generics.GenericAPIView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, *args, **kwargs):
        print("I'm inside the view")
        redirect = request.GET.get('all the data')
        #This is the view I'm trying to pass data to
        

utils.py

def get_endpoint(payload):
    qs = '?'+ urlencode(payload)
    reverse_url = reverse('myapp-start-assessment')
    url = reverse_url + qs
    print(url)
    return HttpResponseRedirect(url)

utils.py中url的输出为:

/api/v2/myapp/startconversation?contact_uuid=67460e74-02e3-11e8-b443-00163e990bdb&choices=None&value=&cardType=&step=None&optionId=None&path=&title=&description=&message=

错误:

    return json.dumps(*args, **kwargs)
  File "/usr/local/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/local/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/local/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 67, in default
    return super().default(obj)
  File "/usr/local/lib/python3.6/json/encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type 'HttpResponseRedirect' is not JSON serializable

我不明白为什么我会看到这个 JSON 不可序列化错误。如果我使用 JsonResponse 或 redirect.

也是同样的问题

尝试稍微更改一下您的代码:

def get_endpoint(payload):
    qs = '?'+ urlencode(payload)
    reverse_url = reverse('myapp-start-assessment')
    url = reverse_url + qs
    print(url)
    return url  # return url not Response

然后在你的 EntryLayerView:

def post(self, request, *args, **kwargs):
    body = request.data
    url = get_endpoint(validated_body) #Don't worry about this line
    return HttpResponseRedirect(url)

此外,不要使用 2.. 代码进行重定向,请改用 3..。