简体   繁体   中英

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...

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()

Your post data is wrong, according to the http://pycurl.io/docs/latest/quickstart.html#sending-form-data it is expecting a dict, not a string. ( json.dumps(None) == 'null' )

The error you get from your webserver is most likely related to that.

import pycurl, json

url = "http://localhost:7001/some_url"
c = pycurl.Curl()
data = {'whatever_field': 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM