Posting raw data with Python Posting raw data with Python curl curl

Posting raw data with Python


I've been having similar turmoils with the stdlib packages, until somoneone pointed to the awesome requests that supports basic Http Authentication and other authentication means straight out-of-the-box! And it has a beautiful and simple API it hurts!

requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))

It supports a host of other necessary features (e.g HTTPS, Digest Authentication, etc) Please check it out if u must...


While editing my post to include some source, I thought I'd have another crack at httplib2 (mainly because it's comparatively small and pretty compared to the others) and noticed that there's a gaping bug in that its add_credentials(..) method doesn't actually do anything. You can work around this by specifying the header (as I did with urllib2) like this:

resp, content = httplib2.Http().request(URL, "POST", body=DATA, headers={    "Authorization": "Basic %s" % base64.encodestring('%s:%s' %(USERNAME, PASSWORD)})

And this works.


Voidspace has an excellent article on using basic auth with urllib2. I've copied the appropriate code snippet below, changed to use POST.

import urllib2theurl = 'http://www.someserver.com/toplevelurl/somepage.htm'username = 'johnny'password = 'XXXXXX'passman = urllib2.HTTPPasswordMgrWithDefaultRealm()passman.add_password(None, theurl, username, password)authhandler = urllib2.HTTPBasicAuthHandler(passman)opener = urllib2.build_opener(authhandler)urllib2.install_opener(opener)pagehandle = urllib2.urlopen(theurl, open("mytext.xml").read())

Without seeing your code it's hard to say why you would be getting a 400 response.