使用CSRF请求toolbelt多部分上载文件失败

时间:2017-07-25 23:21:50

标签: python django file-upload multipart django-rest-framework

我正在尝试使用python Multipart数据编码器(http://toolbelt.readthedocs.io/en/latest/uploading-data.html)将我的DRF后端的.ipa文件上传到第三方应用。但是,我收到以下错误 -

  

('连接已中止。',BrokenPipeError(32,' Broken pipe'))

如果我删除了' rb'属性,我得到以下错误 -

  

' UTF-8'编解码器不能解码位置10中的字节0xe3:无效的连续字节

有人可以指出这里有什么问题吗?顺便说一句,我决定使用请求工具带,因为我可能会上传大文件。

from django.views.generic import View

from django.conf import settings
import os
import requests #sudo pip install requests, it's an external library
from requests_toolbelt.multipart.encoder import MultipartEncoder #pip install requests-toolbelt



class upload_binary(generics.GenericAPIView):

def post(self, request, format=None):

    URL = "http://localhost:9020/"
    csrf = requests.get(URL).cookies['csrftoken']

    post_url = "http://localhost:9020/upload/"
    upload_file_name = "SomeApp.ipa"
    media_dir = settings.MEDIA_ROOT
    upload_file_path = os.path.join(media_dir, upload_file_name)


    filedata = MultipartEncoder(fields = {
        'csrfmiddlewaretoken': csrf, 'file1': ('file', open(upload_file_path, 'rb'))
    }) 
    headersdict = {'X-CSRFToken': csrf, 'Content-Type': filedata.content_type}
    upload_bin_req = requests.post(post_url, data = filedata,  headers = headersdict)

    return JsonResponse({})

1 个答案:

答案 0 :(得分:0)

自己回答这个问题,万一人们需要知道。显然,第三方应用程序上的CSRF导致了这个问题。我必须通过禁用相关视图的CSRF来更新第三方代码以允许REST访问我。我必须导入csrf_exempt并装饰有问题的视图,如下所示 -

    from django.views.decorators.csrf import csrf_exempt

    ...
    ...
   @csrf_exempt 
   def the_third_party_view_I_was_calling(request):

如果有人知道更好的解决方案来解决这个问题而不禁用CSRF,请告知我们。