使用带有请求的多部分/表单数据的 POST 的 python 设置边界 [英] python set-up boundary for POST using multipart/form-data with requests

查看:25
本文介绍了使用带有请求的多部分/表单数据的 POST 的 python 设置边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用请求发送文件,但服务器使用 ***** 设置的固定边界.我只能发送一个文件,但 requests 模块创建了一个随机边界.我如何覆盖它?

I want to send a file using requests but the server works with a fixed boundary set at *****. I'm only able to send a file but the requests module creates a random boundary. How do I overwrite it?

import requests

url='http://xxx.xxx.com/uploadfile.php'
fichier= {'uploadedfile':open('1103290736_2016_03_23_13_32_55.zip','rb')}
headers2={'Connection':'Keep-Alive','User-Agent':'Dalvik/1.6.0 (Linux; U; Android 4.4.2; S503+ Build/KOT49H)','Accept-Encoding':'gzip'}
session= requests.Session()
session.post(url,headers=headers2,files=fichier)
session.close()

推荐答案

天哪,这是一台非常坏的服务器.如果可以,请修复服务器.

Boy, that's one very broken server. If you can, fix the server instead.

你不能告诉 requests 选择什么边界.您可以改为使用 email.mime:

You can't tell requests what boundary to pick. You can instead build your own multipart/form-data payload, using the email.mime package:

from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

related = MIMEMultipart('form-data', '*****')  # second argument is the boundary.
file_part = MIMEApplication(
    open('1103290736_2016_03_23_13_32_55.zip', 'rb').read(),
    # optional: set a subtype: 'zip',
)
file_part.add_header('Content-disposition', 'form-data; name="uploadedfile"')
related.attach(file_part)

body = related.as_string().split('

', 1)[1]
headers = dict(related.items())
headers['User-Agent'] = 'Dalvik/1.6.0 (Linux; U; Android 4.4.2; S503+ Build/KOT49H)'

r = session.post(url, data=body, headers=headers)

这设置 Content-Type: multipart/form-data;bounding="*****" 作为header,body 使用***** 作为边界(适当的-- pre-和后缀).

This sets Content-Type: multipart/form-data; boundary="*****" as the header, and the body uses ***** as the boundary (with appropriate -- pre- and postfixes).

这篇关于使用带有请求的多部分/表单数据的 POST 的 python 设置边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆