Search code examples
pythoncurlpycurl

Curl POST into pycurl code


I'm trying to convert following curl request into pycurl:

curl -v \
--user username:passwd \
-H X-Requested-By:MyClient \
-H Accept:application/json \
-X POST \
http://localhost:7001/some_context

And it works. The following doesn't work:

import pycurl, json

url = "http://localhost:7001/some_context"
c = pycurl.Curl()
data = json.dumps(None)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HTTPHEADER, ['Accept: application/json', 'X-Requested-By:MyClient'])
c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.USERPWD, "username:passwd")
c.perform()

But executing this I have an error 415: Unsupported media type. Do you have any idea? I would rather stay with pycurl- I know about requests library...


Solution

  • This script mimicks your curl command line except for the URL. I have replaced your URL so that we can both test the same server.

    import pycurl, json
    
    url = "http://localhost:7001/some_url"
    url= 'http://httpbin.org/post'
    c = pycurl.Curl()
    c.setopt(pycurl.POST, 1)
    c.setopt(pycurl.POSTFIELDSIZE, 0)
    c.setopt(pycurl.URL, url)
    c.setopt(pycurl.HTTPHEADER, ['Accept: application/json',
                                 'X-Requested-By:MyClient',
                                 'Content-Type:',
                                 'Content-Length:'])
    c.setopt(pycurl.VERBOSE, 1)
    c.setopt(pycurl.USERPWD, "username:passwd")
    c.perform()