从curl到pycurl-如何制作多部分零件-与curl配合使用pycurl失败422

时间:2018-10-31 20:59:03

标签: python curl http-post pycurl

我有一篇很好的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

我在做什么错了?

1 个答案:

答案 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)