【问题标题】:requests: post multipart/form-data请求:发布多部分/表单数据
【发布时间】:2016-11-11 05:29:38
【问题描述】:

我的 API:

class FileView(APIView):
    parser_classes = (MultiPartParser,)
    def post(self, request):
        do something with request.FILES.dict().iteritems()

我的requests 文件:

try:
    headers = {
        'content-type': "multipart/form-data",
        'authorization': "Basic ZXNlbnRpcmVcYdddddddddddddd",
        'cache-control': "no-cache",
    }
    myfile = {"file": ("filexxx", open(filepath, "rb"))}

    response = requests.request("POST", verify=False, url=url, data=myfile, headers=headers)

    print(response.text)
except Exception as e:
    print "Exception:", e

错误:

“多部分表单解析错误 - 多部分中的边界无效:无”

发布文件的正确方法是什么?谢谢

请求。版本 '2.10.0'

【问题讨论】:

    标签: python django-rest-framework python-requests


    【解决方案1】:

    从标题中删除了“内容类型”,现在可以使用了

    try:
        headers = {
            'authorization': "Basic ZXNlbnRpcmVcYdddddddddddddd",
            'cache-control': "no-cache",
        }
        myfile = {"file": ("filexxx", open(filepath, "rb"))}
    
        response = requests.request("POST", verify=False, url=url, data=myfile, headers=headers)
    
        print(response.text)
    except Exception as e:
        print "Exception:", e
    

    【讨论】:

    • 让请求设置内容类型。在请求标头中,content-type='multipart/form-data; boundary=f0d7eb0b58c94f8ea3e665e28cffffdc' 的值根据请求而变化。
    • 是的!当content-type='multipart/form-data 浏览器在发布请求时添加这个boundary 参数时。所以从python 完全没有必要! Distill-Networks 等反抓取工具可以使用此参数轻松检测 python scraper。
    • Whatttttttttt!我必须找到这个解决方案 3 天。
    猜你喜欢
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2022-11-19
    • 1970-01-01
    • 2018-03-19
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多