字符串的索引必须是Django的REST框架整数

时间:2019-02-01 13:29:20

标签: python json django django-rest-framework

我有一个很大的序列化json字段,我试图从中提取多个密钥,然后构造另一个json并通过请求发送。

示例:

class ACtionViewSet(viewsets.ModelViewSet):
    logger = logging.getLogger('django')

    """
    API endpoint
    """
    queryset = Action.objects.all()
    serializer_class = ActionSerializer
    filter_backends = (filters.OrderingFilter,
                       filters.SearchFilter, DjangoFilterBackend)
    filterset_class = ActionFilter

    # create new action for this workflow
    def create(self, request, *args, **kwargs):
        serializer = ActionSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            encode_data = json.dumps(serializer.data)
            wanted_key = ['task', 'task_default', 'slug']
            new_action = {x: encode_data[x] for x in wanted_key if x in encode_data}
            print(new_action)
            workflow = json.dumps(new_action)
            response = requests.post(
                url='{}/workflows'.format(MISTRAL_URL),
                json=workflow,
                headers=headers
            )
            # logging.debug(f"{self.response}")
            return Response({'response': response}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

错误是

string indices must be integers

跟踪:

File "/home/copser/.local/share/virtualenvs/api-IztWJwuB/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/home/copser/.local/share/virtualenvs/api-IztWJwuB/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = self.process_exception_by_middleware(e, request)

File "/home/copser/.local/share/virtualenvs/api-IztWJwuB/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  124.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/copser/.local/share/virtualenvs/api-IztWJwuB/lib/python3.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/home/copser/.local/share/virtualenvs/api-IztWJwuB/lib/python3.7/site-packages/rest_framework/viewsets.py" in view
  116.             return self.dispatch(request, *args, **kwargs)

File "/home/copser/.local/share/virtualenvs/api-IztWJwuB/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
  495.             response = self.handle_exception(exc)

File "/home/copser/.local/share/virtualenvs/api-IztWJwuB/lib/python3.7/site-packages/rest_framework/views.py" in handle_exception
  455.             self.raise_uncaught_exception(exc)

File "/home/copser/.local/share/virtualenvs/api-IztWJwuB/lib/python3.7/site-packages/rest_framework/views.py" in dispatch
  492.             response = handler(request, *args, **kwargs)

File "/home/copser/Documents/Project/api/src/action/views.py" in create
  76.             new_workflow = {x: encode_data[x] for x in wanted_key if x in encode_data}

File "/home/copser/Documents/Project/NjiNN/njinn/api/src/action/views.py" in <dictcomp>
  76.             new_action = {x: encode_data[x] for x in wanted_key if x in encode_data}

Exception Type: TypeError at /api/v1/action
Exception Value: string indices must be integers

我有点困惑为什么会这样,所以有人可以解释一下这里发生了什么,谢谢

2 个答案:

答案 0 :(得分:2)

错误告诉您必须使用整数作为字符串索引,即"some string"[0]有效,"some string"['test']将引发上述问题。

这给您一个提示,可以看哪里!即encode_datajson.dumps生成的字符串。

您可能可以放下json.dumps,或者如果json.loads是字符串,则可以使用serialiser.data

换句话说:

$ json.loads('{"foo": 123}')['foo']
> 123


$ json.dumps({'foo': 123})['foo']
> TypeError: string indices must be integers

答案 1 :(得分:1)

json.dumps返回一个字符串,表示encode_data是一个字符串,而不是字典。

如果serializer.data已经是字典,则按原样使用它;如果它是字符串,则使用json.loads(serializer.data)

此行将触发错误:
new_action = {x: encode_data[x] for x in wanted_key if x in encode_data}

在python中,字符串是可迭代的,但只能通过整数键(如列表)进行访问。

my_string = "01234"
my_char = my_string[3] # result is "3"

但是您正在尝试像这样访问它:

my_data = my_string["key"]

不起作用。