• June 1, 2024


Python requests library combine HTTPProxyAuth with ...

Python requests library combine HTTPProxyAuth with …

Found an example on HTTPProxyAuth usage here
But I’m hoping for a sample on usage with both HTTPProxyAuth and HTTPBasicAuth IE I need to pass a server, username and password through the proxy and a username and password to a web page…
Thanks in advance.
asked Jan 26 ’12 at 22:00
For Basic Authentication you can Httplib2 module of python. An example is given below. For more details check this
>>>import lib2
>>>h = (“”)
>>>d_credentials(‘name’, ‘password’)
>>>resp, content = quest(“,
“PUT”, body=”This is text”,
I don’t think Httplib2 provides the proxy support. Check the link –
swiftBoy34. 3k26 gold badges131 silver badges127 bronze badges
answered Jun 8 ’12 at 12:48
AmeetAmeet519 bronze badges
Unfortunately, HTTPProxyAuth is a child of HTTPBasicAuth and overrides its behaviour (please see requests/).
However, you can add both the required headers to your request by making a new class that implements both behaviours:
class HTTPBasicAndProxyAuth:
def __init__(self, basic_up, proxy_up):
# basic_up is a tuple with username, password
sic_auth = HTTPBasicAuth(*basic_up)
# proxy_up is a tuple with proxy username, password
oxy_auth = HTTPProxyAuth(*proxy_up)
def __call__(self, r):
# this emulates what basicauth and proxyauth do in their __call__()
# first add r. headers[‘Authorization’]
r = sic_auth(r)
# then add r. headers[‘Proxy-Authorization’]
r = oxy_auth(r)
# and return the request, as the auth object should do
return r
answered Apr 1 ’14 at 6:50
Charl BothaCharl Botha3, 99832 silver badges48 bronze badges
It’s not pretty but you can provide separate BasicAuth credentials in both the Proxy AND the restricted page URLs.
For example:
proxies = {
“”: “myproxyusername:mysecret@webproxy:8080/”,
“”: “myproxyusername:mysecret@webproxy:8080/”, }
r = (“”, proxies=proxies)
answered Feb 9 ’15 at 15:06
Not the answer you’re looking for? Browse other questions tagged python proxy -request python-requests or ask your own question.
Python Examples of requests.auth.HTTPProxyAuth - Program ...

Python Examples of requests.auth.HTTPProxyAuth – Program …

The following are 6
code examples for showing how to use ().
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don’t like,
and go to the original project or source file by following the links above each may check out the related API usage on the may also want to check out all available functions/classes of the module, or try the search function. Example 1def _to_server(self, logVal):
if [‘protocol’]! = None:
c_url = [‘protocol’] + “” + [‘address’] + “:” + str([‘port’])
c_url = [‘address’] + “:” + str([‘port’])
(self. LOG_CLASS, “Sending json to: ” + c_url)
headers = {“User-Agent”: “Mozilla/5. 0 (X11; Linux x86_64) AppleWebKit/537. 36 (KHTML, like Gecko) Chrome/66. 0. 3359. 181 Safari/537. 36”}
if ‘use_proxy’ in list(()) and [‘use_proxy’] is True:
if “proxy_auth” in list(()):
cauth = HTTPProxyAuth([‘proxy_auth’][‘username’], [‘proxy_auth’][‘password’])
r = (c_url, json=logVal, [‘proxies’], auth = cauth, headers = headers)
r = (c_url, json=logVal, [‘proxies’], headers = headers)
r = (c_url, json=logVal, headers = headers)
(self. LOG_CLASS, “Status Code: ” + str(atus_code), imp = True) Example 2def _handle_basic_auth_407(self, r, kwargs):
if is not None:
prep = r. ()
if not hasattr(prep, ‘_cookies’):
prep. _cookies = questsCookieJar()
cookies. extract_cookies_to_jar(prep. _cookies, quest, )
epare_cookies(prep. _cookies)
oxy_auth = TPProxyAuth(oxy_username,
prep = oxy_auth(prep)
_r = r. (prep, **kwargs)
quest = prep
return _r Example 3def _handle_basic_auth_407(self, r, kwargs):
return _r Example 4def _handle_basic_auth_407(self, r, kwargs):
return _r Example 5def test_post_init_proxy_auth(self):
“””Set proxy auth info after constructing PACSession, and ensure that PAC proxy URLs then reflect it. “””
sess = PACSession(pac=PACFile(proxy_pac_js_tpl% ‘PROXY a:80;’))
with _patch_request_base() as request:
(arbitrary_url) # Prime proxy resolver state.
get_call(arbitrary_url, ‘a:80’), ])
oxy_auth = HTTPProxyAuth(‘user’, ‘pwd’)
get_call(arbitrary_url, ‘user:pwd@a:80’), ]) Example 6def alert(self, matches):
body = ‘⚠ *%s* ⚠ “`n’% (eate_title(matches))
for match in matches:
body += str(BasicMatchString(, match))
# Separate text of aggregated alerts with dashes
if len(matches) > 1:
body += ‘n—————————————-n’
if len(body) > 4095:
body = body[0:4000] + “n⚠ *message was cropped according to telegram limits! * ⚠”
body += ‘ “`’
headers = {‘content-type’: ‘application/json’}
# set proxy, if it was provided
proxies = {”: egram_proxy} if egram_proxy else None
auth = HTTPProxyAuth(egram_proxy_login, egram_proxy_password) if egram_proxy_login else None
payload = {
‘chat_id’: egram_room_id,
‘text’: body,
‘parse_mode’: ‘markdown’,
‘disable_web_page_preview’: True}
response = (, (payload, cls=DateTimeEncoder), headers=headers, proxies=proxies, auth=auth)
response. raise_for_status()
except RequestException as e:
raise EAException(“Error posting to Telegram:%s. Details:%s”% (e, “” if sponse is None else e. ))
“Alert sent to Telegram room%s”% egram_room_id)
requests.auth — Requests 2.26.0 documentation

requests.auth — Requests 2.26.0 documentation

# -*- coding: utf-8 -*-
This module contains the authentication handlers for Requests.
import os
import re
import time
import hashlib
import threading
import warnings
from base64 import b64encode
from import urlparse, str, basestring
from. cookies import extract_cookies_to_jar
from. _internal_utils import to_native_string
from import parse_dict_header
CONTENT_TYPE_FORM_URLENCODED = ‘application/x-www-form-urlencoded’
CONTENT_TYPE_MULTI_PART = ‘multipart/form-data’
def _basic_auth_str(username, password):
“””Returns a Basic Auth string. “””
# “I want us to put a big-ol’ comment on top of it that
# says that this behaviour is dumb but we need to preserve
# it because people are relying on it. ”
# – Lukasa
# These are here solely to maintain backwards compatibility
# for things like ints. This will be removed in 3. 0. 0.
if not isinstance(username, basestring):
“Non-string usernames will no longer be supported in Requests ”
“3. Please convert the object you’ve passed in ({! r}) to ”
“a string or bytes object in the near future to avoid ”
“problems. “(username),
category=DeprecationWarning, )
username = str(username)
if not isinstance(password, basestring):
“Non-string passwords will no longer be supported in Requests ”
“problems. “(type(password)),
password = str(password)
# — End Removal —
if isinstance(username, str):
username = (‘latin1’)
if isinstance(password, str):
password = (‘latin1’)
authstr = ‘Basic ‘ + to_native_string(
b64encode(b’:'((username, password)))())
return authstr
[docs]class AuthBase(object):
“””Base class that all auth implementations derive from”””
def __call__(self, r):
raise NotImplementedError(‘Auth hooks must be callable. ‘)
[docs]class HTTPBasicAuth(AuthBase):
“””Attaches HTTP Basic Authentication to the given Request object. “””
def __init__(self, username, password):
ername = username
ssword = password
def __eq__(self, other):
return all([
ername == getattr(other, ‘username’, None),
ssword == getattr(other, ‘password’, None)])
def __ne__(self, other):
return not self == other
r. headers[‘Authorization’] = _basic_auth_str(ername, ssword)
return r
[docs]class HTTPProxyAuth(HTTPBasicAuth):
“””Attaches HTTP Proxy Authentication to a given Request object. “””
r. headers[‘Proxy-Authorization’] = _basic_auth_str(ername, ssword)
[docs]class HTTPDigestAuth(AuthBase):
“””Attaches HTTP Digest Authentication to the given Request object. “””
# Keep state in per-thread local storage
self. _thread_local = ()
def init_per_thread_state(self):
# Ensure state is initialized just once per-thread
if not hasattr(self. _thread_local, ‘init’):
= True
st_nonce = ”
nce_count = 0
= {}
= None
m_401_calls = None
def build_digest_header(self, method, url):
“””:rtype: str
realm = [‘realm’]
nonce = [‘nonce’]
qop = (‘qop’)
algorithm = (‘algorithm’)
opaque = (‘opaque’)
hash_utf8 = None
if algorithm is None:
_algorithm = ‘MD5’
_algorithm = ()
# lambdas assume digest modules are imported at the top level
if _algorithm == ‘MD5’ or _algorithm == ‘MD5-SESS’:
def md5_utf8(x):
if isinstance(x, str):
x = (‘utf-8’)
return 5(x). hexdigest()
hash_utf8 = md5_utf8
elif _algorithm == ‘SHA’:
def sha_utf8(x):
return a1(x). hexdigest()
hash_utf8 = sha_utf8
elif _algorithm == ‘SHA-256’:
def sha256_utf8(x):
return a256(x). hexdigest()
hash_utf8 = sha256_utf8
elif _algorithm == ‘SHA-512’:
def sha512_utf8(x):
return a512(x). hexdigest()
hash_utf8 = sha512_utf8
KD = lambda s, d: hash_utf8(“%s:%s”% (s, d))
if hash_utf8 is None:
return None
# XXX not implemented yet
entdig = None
p_parsed = urlparse(url)
#: path is request-uri defined in RFC 2616 which should not be empty
path = or “/”
path += ‘? ‘ +
A1 = ‘%s:%s:%s’% (ername, realm, ssword)
A2 = ‘%s:%s’% (method, path)
HA1 = hash_utf8(A1)
HA2 = hash_utf8(A2)
if nonce == st_nonce:
nce_count += 1
nce_count = 1
ncvalue = ‘%08x’% nce_count
s = str(nce_count)(‘utf-8’)
s += (‘utf-8’)
s += ()(‘utf-8’)
s += os. urandom(8)
cnonce = (a1(s). hexdigest()[:16])
if _algorithm == ‘MD5-SESS’:
HA1 = hash_utf8(‘%s:%s:%s’% (HA1, nonce, cnonce))
if not qop:
respdig = KD(HA1, “%s:%s”% (nonce, HA2))
elif qop == ‘auth’ or ‘auth’ in (‘, ‘):
noncebit = “%s:%s:%s:%s:%s”% (
nonce, ncvalue, cnonce, ‘auth’, HA2)
respdig = KD(HA1, noncebit)
# XXX handle auth-int.
st_nonce = nonce
# XXX should the partial digests be encoded too?
base = ‘username=”%s”, realm=”%s”, nonce=”%s”, uri=”%s”, ‘
‘response=”%s”‘% (ername, realm, nonce, path, respdig)
if opaque:
base += ‘, opaque=”%s”‘% opaque
if algorithm:
base += ‘, algorithm=”%s”‘% algorithm
if entdig:
base += ‘, digest=”%s”‘% entdig
if qop:
base += ‘, qop=”auth”, nc=%s, cnonce=”%s”‘% (ncvalue, cnonce)
return ‘Digest%s’% (base)
def handle_redirect(self, r, **kwargs):
“””Reset num_401_calls counter on redirects. “””
if _redirect:
m_401_calls = 1
def handle_401(self, r, **kwargs):
Takes the given response and tries digest-auth, if needed. :rtype: sponse
# If response is not 4xx, do not auth
# See if not 400 <= atus_code < 500: if is not None: # Rewind the file position indicator of the body to where # it was to resend the request. () s_auth = r. ('www-authenticate', '') if 'digest' in () and m_401_calls < 2: m_401_calls += 1 pat = mpile(r'digest ', flags=re. IGNORECASE) = parse_dict_header(('', s_auth, count=1)) # Consume content and release the original connection # to allow our new request to reuse the same one. ntent prep = r. () extract_cookies_to_jar(prep. _cookies, quest, ) epare_cookies(prep. _cookies) prep. headers['Authorization'] = _digest_header(, ) _r = r. (prep, **kwargs) (r) quest = prep return _r # Initialize per-thread state, if needed it_per_thread_state() # If we have a saved nonce, skip the 401 if st_nonce: r. headers['Authorization'] = _digest_header(, ) try: = () except AttributeError: # In the case of HTTPDigestAuth being reused and the body of # the previous request was a file-like object, pos has the # file position of the previous body. Ensure it's set to # None. gister_hook('response', self. handle_401) gister_hook('response', self. handle_redirect) return not self == other

Frequently Asked Questions about httpproxyauth

Leave a Reply

Your email address will not be published. Required fields are marked *