本文整理匯總了Python中urllib.request.HTTPSHandler方法的典型用法代碼示例。如果您正苦於以下問題:Python request.HTTPSHandler方法的具體用法?Python request.HTTPSHandler怎麽用?Python request.HTTPSHandler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類urllib.request
的用法示例。
在下文中一共展示了request.HTTPSHandler方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_access_token
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def get_access_token(self, code, state=None):
'''
In callback url: http://host/callback?code=123&state=xyz
use code and state to get an access token.
'''
kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code)
if self._redirect_uri:
kw['redirect_uri'] = self._redirect_uri
if state:
kw['state'] = state
opener = build_opener(HTTPSHandler)
request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw))
request.get_method = _METHOD_MAP['POST']
request.add_header('Accept', 'application/json')
try:
response = opener.open(request, timeout=TIMEOUT)
r = _parse_json(response.read())
if 'error' in r:
raise ApiAuthError(str(r.error))
return str(r.access_token)
except HTTPError as e:
raise ApiAuthError('HTTPError when get access token')
示例2: GetHandlers
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def GetHandlers(self):
"""Retrieve the appropriate urllib handlers for the given configuration.
Returns:
A list of urllib.request.BaseHandler subclasses to be used when making
calls with proxy.
"""
handlers = []
if self.ssl_context:
handlers.append(HTTPSHandler(context=self.ssl_context))
if self.proxies:
handlers.append(ProxyHandler(self.proxies))
return handlers
示例3: get_access_token
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def get_access_token(self, code, state=None):
'''
In callback url: http://host/callback?code=123&state=xyz
use code and state to get an access token.
'''
kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code)
if self._redirect_uri:
kw['redirect_uri'] = self._redirect_uri
if state:
kw['state'] = state
opener = build_opener(HTTPSHandler)
request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw))
request.get_method = _METHOD_MAP['POST']
request.add_header('Accept', 'application/json')
try:
response = opener.open(request, timeout=TIMEOUT)
r = _parse_json(response.read())
if 'error' in r:
raise ApiAuthError(str(r.error))
return str(r.access_token)
except HTTPError as e:
raise ApiAuthError('HTTPError when get access token')
示例4: __init__
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def __init__(self, ssl_config): # pylint: disable=E1002
"""Initialize"""
if PY2:
urllib2.HTTPSHandler.__init__(self)
else:
super().__init__() # pylint: disable=W0104
self._ssl_config = ssl_config
示例5: _http
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def _http(self, _method, _path, **kw):
data = None
params = None
if _method=='GET' and kw:
_path = '%s?%s' % (_path, _encode_params(kw))
if _method in ['POST', 'PATCH', 'PUT']:
data = bytes(_encode_json(kw), 'utf-8')
url = '%s%s' % (_URL, _path)
opener = build_opener(HTTPSHandler)
request = Request(url, data=data)
request.get_method = _METHOD_MAP[_method]
if self._authorization:
request.add_header('Authorization', self._authorization)
if _method in ['POST', 'PATCH', 'PUT']:
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
try:
response = opener.open(request, timeout=TIMEOUT)
is_json = self._process_resp(response.headers)
if is_json:
return _parse_json(response.read().decode('utf-8'))
except HTTPError as e:
is_json = self._process_resp(e.headers)
if is_json:
json = _parse_json(e.read().decode('utf-8'))
else:
json = e.read().decode('utf-8')
req = JsonObject(method=_method, url=url)
resp = JsonObject(code=e.code, json=json)
if resp.code==404:
raise ApiNotFoundError(url, req, resp)
raise ApiError(url, req, resp)
示例6: get_access_token
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def get_access_token(self, code, state=None):
'''
In callback url: http://host/callback?code=123&state=xyz
use code and state to get an access token.
'''
kw = dict(
client_id=self._client_id,
client_secret=self._client_secret,
code=code)
if self._redirect_uri:
kw['redirect_uri'] = self._redirect_uri
if state:
kw['state'] = state
opener = build_opener(HTTPSHandler)
request = Request(
'https://github.com/login/oauth/access_token',
data=_encode_params(kw))
request.get_method = _METHOD_MAP['POST']
request.add_header('Accept', 'application/json')
try:
response = opener.open(request, timeout=TIMEOUT)
r = _parse_json(response.read())
if 'error' in r:
raise ApiAuthError(str(r.error))
return str(r.access_token)
except HTTPError as e:
raise ApiAuthError('HTTPError when get access token')
示例7: _http
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def _http(self, _method, _path, **kw):
data = None
params = None
if _method == 'GET' and kw:
_path = '%s?%s' % (_path, _encode_params(kw))
if _method in ['POST', 'PATCH', 'PUT']:
data = bytes(_encode_json(kw), 'utf-8')
url = '%s%s' % (_URL, _path)
opener = build_opener(HTTPSHandler)
request = Request(url, data=data)
request.get_method = _METHOD_MAP[_method]
if self._authorization:
request.add_header('Authorization', self._authorization)
if _method in ['POST', 'PATCH', 'PUT']:
request.add_header('Content-Type',
'application/x-www-form-urlencoded')
class Resp():
code = None
resp = Resp()
req = None
try:
response = opener.open(request, timeout=TIMEOUT)
is_json = self._process_resp(response.headers)
if is_json:
return _parse_json(response.read().decode('utf-8'))
except HTTPError as e:
is_json = self._process_resp(e.headers)
if is_json:
json = _parse_json(e.read().decode('utf-8'))
else:
json = e.read().decode('utf-8')
req = JsonObject(method=_method, url=url)
resp = JsonObject(code=e.code, json=json)
finally:
if resp.code == 404:
raise ApiNotFoundError(url, req, resp)
elif req:
raise ApiError(url, req, resp)
示例8: hashed_download
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def hashed_download(url, temp, digest):
"""Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``,
and return its path."""
# Based on pip 1.4.1's URLOpener but with cert verification removed
def opener():
opener = build_opener(HTTPSHandler())
# Strip out HTTPHandler to prevent MITM spoof:
for handler in opener.handlers:
if isinstance(handler, HTTPHandler):
opener.handlers.remove(handler)
return opener
def read_chunks(response, chunk_size):
while True:
chunk = response.read(chunk_size)
if not chunk:
break
yield chunk
response = opener().open(url)
path = join(temp, urlparse(url).path.split('/')[-1])
actual_hash = sha256()
with open(path, 'wb') as file:
for chunk in read_chunks(response, 4096):
file.write(chunk)
actual_hash.update(chunk)
actual_digest = actual_hash.hexdigest()
if actual_digest != digest:
raise HashError(url, path, actual_digest, digest)
return path
示例9: __init__
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def __init__(self, base_url="", tag="", cookiejar=None, debug=False):
self.tag = tag
hh = urllib2.HTTPHandler( debuglevel=1 if debug else 0)
hsh = urllib2.HTTPSHandler(debuglevel=1 if debug else 0)
cp = urllib2.HTTPCookieProcessor(cookiejar)
self._opener = urllib2.build_opener(hh, hsh, cp)
scheme, netloc, path, q, f = urlparse.urlsplit(base_url, "http")
if not netloc:
netloc, _, path = path.partition('/')
self.base_url = urlparse.urlunsplit((scheme, netloc, path, q, f))
示例10: __init__
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def __init__(self, cacert_file):
self.cacert_file = cacert_file
request.HTTPSHandler.__init__(self)
示例11: __init__
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def __init__(self, http_proxy=None, https_proxy=None, cafile=None,
disable_certificate_validation=False):
self._http_proxy = http_proxy
self._https_proxy = https_proxy
self.proxies = {}
if self._https_proxy:
self.proxies['https'] = str(self._https_proxy)
if self._http_proxy:
self.proxies['http'] = str(self._http_proxy)
self.disable_certificate_validation = disable_certificate_validation
self.cafile = None if disable_certificate_validation else cafile
# Initialize the context used to generate the HTTPSHandler.
self.ssl_context = self._InitSSLContext(
self.cafile, self.disable_certificate_validation)
示例12: get
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def get(self, uri, params={}, headers={}, with_status_code=False, timeout=10, user=None, password=None):
data = None # always none in GET
if params:
uri = "%s?%s" % (uri, urlencode(params))
# SSL, user/password and basic
# NOTE: currently don't manage ssl & user/password
if uri.startswith('https://'):
handler = HTTPSHandler(context=self.ssl_context)
elif user and password:
passwordMgr = HTTPPasswordMgrWithDefaultRealm()
passwordMgr.add_password(None, uri, user, password)
handler = HTTPBasicAuthHandler(passwordMgr)
else:
handler = HTTPHandler
url_opener = build_opener(handler)
req = Request(uri, data)
req.get_method = lambda: 'GET'
for (k, v) in headers.items():
req.add_header(k, v)
request = url_opener.open(req, timeout=timeout)
response = request.read()
status_code = request.code
request.close()
if not with_status_code:
return response
else:
return (status_code, response)
示例13: GetProxiedOpener
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def GetProxiedOpener():
testURL = 'https://stooq.com'
userName, password = 'mUser', 'SecureAccess'
context = ssl._create_unverified_context()
handler = webRequest.HTTPSHandler(context=context)
i = -1
functioning = False
global currentProxyServer
while not functioning and i < len(proxyList):
if i >=0 or currentProxyServer==None: currentProxyServer = proxyList[i]
proxy = webRequest.ProxyHandler({'https': r'http://' + userName + ':' + password + '@' + currentProxyServer})
auth = webRequest.HTTPBasicAuthHandler()
opener = webRequest.build_opener(proxy, auth, handler)
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.1 Safari/603.1.30')]
#opener.addheaders = [('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15')]
#opener.addheaders = [('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763')]
try:
conn = opener.open(testURL)
print('Proxy ' + currentProxyServer + ' is functioning')
functioning = True
except:
print('Proxy ' + currentProxyServer + ' is not responding')
i+=1
return opener
#-------------------------------------------- Classes -----------------------------------------------
示例14: __init__
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def __init__(self, client_cert=None, client_key=None, unix_socket=None, **kwargs):
urllib_request.HTTPSHandler.__init__(self, **kwargs)
self.client_cert = client_cert
self.client_key = client_key
self._unix_socket = unix_socket
示例15: check_proxy
# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPSHandler [as 別名]
def check_proxy(q):
"""
check proxy for and append to working proxies
:param q:
"""
if not q.empty():
proxy = q.get(False)
proxy = proxy.replace("\r", "").replace("\n", "")
try:
opener = rq.build_opener(
rq.ProxyHandler({'https': 'https://' + proxy}),
rq.HTTPHandler(),
rq.HTTPSHandler()
)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
rq.install_opener(opener)
req = rq.Request('https://api.ipify.org/')
if rq.urlopen(req).read().decode() == proxy.partition(':')[0]:
proxys_working_list.update({proxy: proxy})
if _verbose:
print(bcolors.OKGREEN + " --[+] ", proxy, " | PASS" + bcolors.ENDC)
else:
if _verbose:
print(" --[!] ", proxy, " | FAILED")
except Exception as err:
if _verbose:
print(" --[!] ", proxy, " | FAILED")
if _debug:
logger.error(err)
pass