What is the cleanest way to do HTTP POST with basi

2019-02-05 16:53发布

问题:

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

Using only the Python core libs.

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



回答2:

Hackish workaround works:

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

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



回答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