JSONDecodeError:在POST请求中将文件和json字符串发送到Django视图

时间:2017-08-09 11:16:54

标签: json django http post

我正在以字符串格式发送文件和json对象,如下面multipart/form-data中的POST请求中所示。我无法确定我在这里做错了什么。请求,Django视图代码和堆栈跟踪 -

请求:

 curl -X POST \
  http://127.0.0.1:8000/api/capshots/send-capshot-new-capset/ \
  -H 'authorization: Token 534cec0c2d7f81808600fee15751b4de2b7c1bd1' \
  -H 'cache-control: no-cache' \
  -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
  -F media_file=@/Users/ankit/Desktop/logo.png \
  -F thumbnail_image=@/Users/ankit/Desktop/logo.png \
  -F 'payload='\''{"allow_capset_sharing": true, "description": "Bla blah", "media_type": 1, "content_type_list": ["group", "directmessagegroup", "temporarygroup"], "object_id_list": [3, 2, 4], "userprofiles_pk": [2, 4, 6], "direct": false}'\'''

代码

@api_view(['POST'])
@permission_classes((IsAuthenticated,))
@authentication_classes((TokenAuthentication,))
def send_capshot_new_capset(request):
    # content_type could be `group`, `temporarygroup`, `directmessagegroup`
    """
    {
        "content_type_list" : ['group', 'directmessagegroup', 'temporarygroup'],
        "object_id_list" : ['3', '2', '4'],
        "userprofiles_pk" : [2, 4, 6],
        "direct" : false
    }
    """
    created_by = request.user.userprofile
    payload_json_str = request.data['payload']
    print(payload_json_str)
    payload_json = json.loads(payload_json_str)
    content_type_list = payload_json['content_type_list']
    object_id_list = payload_json['object_id_list']
    allow_sharing = payload_json['allow_capset_sharing']
    description=payload_json['description']
    media_type=payload_json['media_type']

    # Upload capshot's media file and thumbnail
    from boto.s3.connection import S3Connection
    from boto.s3.key import Key

    media_file = request.FILES['media_file']
    thumbnail_image = request.FILES['thumbnail_image']

    conn = S3Connection(settings.AWS_ACCESS_KEY, settings.AWS_SECRET_KEY)
    bucket = conn.get_bucket('capshot-data')
    k = Key(bucket)

    k.key = "capshots/media/" + datetime.datetime.now().strftime("%d-%m-%y-%H-%M-%S.%f")
    k.set_contents_from_file(media_file)
    media_url = "https://some-url/" + k.key

    k.key = "capshots/thumbnail/" + datetime.datetime.now().strftime("%d-%m-%y-%H-%M-%S.%f")
    k.set_contents_from_file(thumbnail_image)
    thumbnail_image_url = "https://some-url/" + k.key

    # Create Capsets for existing conversations
    for content_type, object_id in zip(content_type_list, object_id_list):

        content_type = ContentType.objects.get(app_label='groups', model=content_type)
        object_id = object_id

        capset = Capset.objects.create(created_by=created_by,
                                       allow_sharing=allow_sharing,
                                       content_type=content_type,
                                       object_id=object_id)
        capshot = Capshot.objects.create(created_by=created_by,
                                         capset=capset,
                                         order=1,
                                         description=description,
                                         media_type=media_type,
                                         media_url=media_url,
                                         thumbnail_image_url=thumbnail_image_url
                                        )

        # Create CapsetReadActivity
        CapsetReadActivity.objects.create(userprofile=request.user.userprofile, capset=capset)

    try:
        userprofiles_pk = payload_json["userprofiles_pk"]
        if len(userprofiles_pk) > 0:
            # DirectMessageGroup
            if payload_json["direct"] is True:
                for userprofile_pk in userprofiles_pk:
                    sender_directmessagegroups_pk = set(UserProfileDirectMessageGroupMembership.objects.filter(userprofile=created_by).values_list('directmessagegroup', flat=True))
                    receiver_directmessagegroups_pk = set(UserProfileDirectMessageGroupMembership.objects.filter(userprofile__pk=userprofile_pk).values_list('directmessagegroup', flat=True))

                    common_directmessagegroup_pk_list = list(sender_directmessagegroups_pk & receiver_directmessagegroups_pk)

                    # if direct message group exists:
                    if len(common_directmessagegroup_pk_list) == 1:
                        # get dmg
                        directmessagegroup = DirectMessageGroup.objects.get(pk=common_directmessagegroup_pk_list[0])

                    else:
                        # create dmg
                        directmessagegroup = DirectMessageGroup.objects.create(created_by=created_by)
                        UserProfileDirectMessageGroupMembership.objects.create(userprofile=created_by, directmessagegroup=directmessagegroup)
                        UserProfileDirectMessageGroupMembership.objects.create(userprofile=UserProfile.objects.get(pk=userprofile_pk), directmessagegroup=directmessagegroup)

                    # create capset, capshot
                    content_type = ContentType.objects.get(app_label='groups', model='directmessagegroup')
                    object_id = directmessagegroup.pk

                    capset = Capset.objects.create(created_by=created_by,
                                                   allow_sharing=allow_sharing,
                                                   content_type=content_type,
                                                   object_id=object_id)
                    capshot = Capshot.objects.create(created_by=created_by,
                                                     capset=capset,
                                                     order=1,
                                                     description=description,
                                                     media_type=media_type,
                                                     media_url=media_url,
                                                     thumbnail_image_url=thumbnail_image_url
                                                    )

                    # Create CapsetReadActivity
                    CapsetReadActivity.objects.create(userprofile=created_by, capset=capset)

            # TemporaryGroup
            else:
                common_temporarygroup_pk_list = None
                for userprofile_pk in userprofiles_pk:
                    if common_temporarygroup_pk_list is None:
                        common_temporarygroup_pk_list = set(UserProfileTemporaryGroupMembership.objects.filter(userprofile__pk=userprofile_pk).values_list('temporarygroup', flat=True))
                    else:
                        common_temporarygroup_pk_list = common_temporarygroup_pk_list & set(UserProfileTemporaryGroupMembership.objects.filter(userprofile__pk=userprofile_pk).values_list('temporarygroup', flat=True))

                common_temporarygroup_pk_list = list(common_temporarygroup_pk_list)
                # if common TG exists
                if len(common_temporarygroup_pk_list) == 1:
                    # get TG
                    temporarygroup = TemporaryGroup.objects.get(pk=common_temporarygroup_pk_list[0])
                else:
                    temporarygroup = TemporaryGroup.objects.create(created_by=created_by)
                    UserProfileTemporaryGroupMembership.objects.create(userprofile=created_by, temporarygroup=temporarygroup)
                    for userprofile_pk in userprofiles_pk:
                        UserProfileTemporaryGroupMembership.objects.create(userprofile=UserProfile.objects.get(pk=userprofile_pk), temporarygroup=temporarygroup)

                # create capset, capshot
                content_type = ContentType.objects.get(app_label='groups', model='temporarygroup')
                object_id = temporarygroup.pk

                capset = Capset.objects.create(created_by=created_by,
                                               allow_sharing=allow_sharing,
                                               content_type=content_type,
                                               object_id=object_id)
                capshot = Capshot.objects.create(created_by=created_by,
                                                 capset=capset,
                                                 order=1,
                                                 description=description,
                                                 media_type=media_type,
                                                 media_url=media_url,
                                                 thumbnail_image_url=thumbnail_image_url
                                                )

                # Create CapsetReadActivity
                CapsetReadActivity.objects.create(userprofile=created_by, capset=capset)

    except: # key userprofiles_pk does not exist
        pass

    return Response({}, status=status.HTTP_201_CREATED)

Stacktrace

Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
'{"allow_capset_sharing": true, "description": "Bla blah", "media_type": 1, "content_type_list": ["group", "directmessagegroup", "temporarygroup"], "object_id_list": [3, 2, 4], "userprofiles_pk": [2, 4, 6], "direct": false}'
Internal Server Error: /api/capshots/send-capshot-new-capset/
Traceback (most recent call last):
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
    response = self.handle_exception(exc)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/rest_framework/decorators.py", line 52, in handler
    return func(*args, **kwargs)
  File "/Users/ankit/projects/indiez/capshot/capshot-be/capshotbackend/capshots/views.py", line 46, in send_capshot_new_capset
    payload_json = json.loads(payload_json_str)
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

0 个答案:

没有答案