Search code examples
pythonrestpostpycurl

Form data in pycurl request


I would like to make following curl request with pycurl:

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

How to put to the postfield things that follow -F options?

I have currently:

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

Solution

  • This is my conversion of your curl script.

    #!/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()
    

    It's not easy finding examples of pycurl on forms. None in the doc, so I downloaded the source and used tests/post_test.py.