我有一篇很好的cURL帖子:
curl -X POST http://some-server.com/working_endpoint-F "package[distro_version_id]=1" -F "package[package_file]=@/tmp/myfile.bin"
当我尝试将其转换为pycurl时,请求失败,并显示422无法处理的实体,服务器说package[package_file]
“必须是多部分表单数据”
import pycurl
c = pycurl.Curl()
c.setopt(pycurl.VERBOSE, 1)
c.setopt(c.URL, 'http://some-server.com/working_endpoint')
c.setopt(c.POST, 1)
c.setopt(c.HTTPPOST, [('package[package_file]', (c.FORM_FILE, '/tmp/myfile.bin'))])
c.setopt(c.HTTPPOST, [('package[distro_version_id]', '1')])
c.perform()
实际上,标题看起来像只有一个参数进入多部分形式
Content-Length: 165
Content-Type: multipart/form-data; boundary=------------------------dee07c93fad525aa
我在做什么错了?
答案 0 :(得分:0)
想通了。
不是像这样对表单数据进行单独的setopt调用
c.setopt(c.HTTPPOST, [('package[package_file]', (c.FORM_FILE, '/tmp/myfile.bin'))])
c.setopt(c.HTTPPOST, [('package[distro_version_id]', '1')])
它需要像这样一个单一的结构在一起
data = [
('package[distro_version_id]', '1'),
('package[package_file]', (
c.FORM_FILE, '/tmp/myfile.bin,
c.FORM_CONTENTTYPE, 'application/octet-stream'
))]
c.setopt(c.HTTPPOST, data)