2017-08-09 64 views
1

我發送文件和json對象爲字符串格式,如下面的multipart/form-data中的POST請求。我無法確定我在這裏做錯了什麼。請求,Django的視圖代碼和堆棧跟蹤 -JSONDecodeError:發送文件和json字符串到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 [email protected]/Users/ankit/Desktop/logo.png \ 
    -F [email protected]/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) 

堆棧跟蹤

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

此代碼在python工作正常:

import json 
s = '{"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}' 
json.loads(s) 
{u'description': u'Bla blah', u'allow_capset_sharing': True, u'content_type_list': [u'group', u'directmessagegroup', u'temporarygroup'], u'direct': False, u'object_id_list': [3, 2, 4], u'userprofiles_pk': [2, 4, 6], u'media_type': 1} 

嘗試添加:

print (request.data['payload']) 

可能是你需要:

payload_json_str = request.POST.get('payload', '{}') 
+0

是的,代碼在我的最終工作正常。我添加了一個打印語句,嘗試打印出來的JSON字符串上的代碼,它仍然工作。在代碼中添加print語句並在編輯中更新堆棧跟蹤。 – anon

+0

更新了打印聲明及其輸出 – anon

+0

你可以把'capshots/views.py'完整的真實代碼,看起來你的例子是錯誤的。用完整的視圖代碼更新了 –

0

試試這個:

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 [email protected]/Users/ankit/Desktop/logo.png \ 
    -F [email protected]/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}' 

在現實中payload_json_str開始和結束'\'但它沒有打印