similar to @ thom-nichols answer; but the HTTPBasicAuthHandler subclass also handles HTTPS requests.
import urllib2 import base64 class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler): '''Preemptive basic auth. Instead of waiting for a 403 to then retry with the credentials, send the credentials if the url is handled by the password manager. Note: please use realm=None when calling add_password.''' def http_request(self, req): url = req.get_full_url() realm = None
here is an example of working with a jenkins server that does not send you 401 http errors (try again using auth). I use urllib2.install_opener to simplify the task.
jenkins_url = "https://jenkins.example.com" username = "johndoe" api_token = "some-cryptic-value" auth_handler = PreemptiveBasicAuthHandler() auth_handler.add_password( realm=None,
dnozay Jun 04 '14 at 22:38 2014-06-04 22:38
source share