What is the cleanest way to do HTTP POST with basic auth in Python?

What is the cleanest way to do HTTP POST with Basic Auth in Python?

Using only the Python core libs.


Solution 1:

Seriously, just use requests:

import requests
resp = requests.post(url, data={}, auth=('user', 'pass'))

It's a pure python library, installing is as easy as easy_install requests or pip install requests. It has an extremely simple and easy to use API, and it fixes bugs in urllib2 so you don't have to. Don't make your life harder because of silly self-imposed requirements.

Solution 2:

Hackish workaround works:

urllib.urlopen("https://username:password@hostname/path", data) 

A lot of people don't realize that the old syntax for specifying username and password in the URL works in urllib.urlopen. It doesn't appear the username or password require any encoding, except perhaps if the password includes an "@" symbol.

Solution 3:

if you define a url, username, password, and some post-data, this should work in Python2...

import urllib2

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
auth_handler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
content = urllib2.urlopen(url, post_data)

example from official Python docs showing Basic Auth in urllib2: * http://docs.python.org/release/2.6/howto/urllib2.html

full tutorial on Basic Authentication using urllib2: * http://www.voidspace.org.uk/python/articles/authentication.shtml