在pycurl请求中表单数据

时间:2015-08-03 14:17:38

标签: python rest post pycurl

我想用pycurl进行以下curl请求:

curl -v \
-H Accept:application/json \
-F "model={
name: 'zxy',
targets: [ 'abc']
}" \
-F "deployment=@/deployments/MyApp.ear" \
-X POST https://abc.cde

如何将 -F 选项后的内容放到后场?

我目前:

c = pycurl.Curl()
c.setopt(pycurl.URL, "https://abc.cde")
c.setopt(pycurl.HTTPHEADER, ['Accept:application/json'])
c.setopt(pycurl.POST, 1)
# set postfield somehow

1 个答案:

答案 0 :(得分:7)

这是我对你的卷曲脚本的转换。

#!/usr/bin/python
import os, sys, pycurl
model = """{
name: 'zxy',
targets: [ 'abc']
}"""
path = '/deployments/MyApp.ear'
c = pycurl.Curl()
c.setopt(pycurl.URL, 'https://abc.cde')
c.setopt(pycurl.HTTPHEADER, ['Accept:application/json'])
send = [("model", model),
        ('deployment', (pycurl.FORM_FILE, path)),]
c.setopt(pycurl.HTTPPOST, send)
#c.setopt(pycurl.VERBOSE, 1)
c.perform()
print c.getinfo(pycurl.RESPONSE_CODE)
c.close()

在表格上找到pycurl的例子并不容易。 doc中没有,因此我下载了source并使用了tests/post_test.py