本文整理汇总了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