當前位置: 首頁>>代碼示例>>Python>>正文


Python request.HTTPBasicAuthHandler方法代碼示例

本文整理匯總了Python中urllib.request.HTTPBasicAuthHandler方法的典型用法代碼示例。如果您正苦於以下問題:Python request.HTTPBasicAuthHandler方法的具體用法?Python request.HTTPBasicAuthHandler怎麽用?Python request.HTTPBasicAuthHandler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在urllib.request的用法示例。


在下文中一共展示了request.HTTPBasicAuthHandler方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: getFile

# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPBasicAuthHandler [as 別名]
def getFile(cls, getfile, unpack=True):
        if cls.getProxy():
            proxy = req.ProxyHandler({'http': cls.getProxy(), 'https': cls.getProxy()})
            auth = req.HTTPBasicAuthHandler()
            opener = req.build_opener(proxy, auth, req.HTTPHandler)
            req.install_opener(opener)
        if cls.ignoreCerts():
            ctx = ssl.create_default_context()
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
            opener = req.build_opener(urllib.request.HTTPSHandler(context=ctx))
            req.install_opener(opener)

        response = req.urlopen(getfile)
        data = response
        # TODO: if data == text/plain; charset=utf-8, read and decode
        if unpack:
            if   'gzip' in response.info().get('Content-Type'):
                buf = BytesIO(response.read())
                data = gzip.GzipFile(fileobj=buf)
            elif 'bzip2' in response.info().get('Content-Type'):
                data = BytesIO(bz2.decompress(response.read()))
            elif 'zip' in response.info().get('Content-Type'):
                fzip = zipfile.ZipFile(BytesIO(response.read()), 'r')
                if len(fzip.namelist())>0:
                    data=BytesIO(fzip.read(fzip.namelist()[0]))
        return (data, response)


    # Feeds 
開發者ID:flipkart-incubator,項目名稱:watchdog,代碼行數:32,代碼來源:Config.py

示例2: urlretrieve

# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPBasicAuthHandler [as 別名]
def urlretrieve(url, filename, data=None, auth=None):
    if auth is not None:
        # https://docs.python.org/2.7/howto/urllib2.html#id6
        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

        # Add the username and password.
        # If we knew the realm, we could use it instead of None.
        username, password = auth
        top_level_url = urlparse(url).netloc
        password_mgr.add_password(None, top_level_url, username, password)

        handler = urllib2.HTTPBasicAuthHandler(password_mgr)

        # create "opener" (OpenerDirector instance)
        opener = urllib2.build_opener(handler)
    else:
        opener = urllib2.build_opener()

    res = opener.open(url, data=data)

    headers = res.info()

    with open(filename, "wb") as fp:
        fp.write(res.read())

    return filename, headers 
開發者ID:wimglenn,項目名稱:johnnydep,代碼行數:28,代碼來源:compat.py

示例3: __open

# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPBasicAuthHandler [as 別名]
def __open(self, url, headers={}, data=None, baseurl=""):
        """Raw urlopen command"""
        if not baseurl:
            baseurl = self.baseurl
        req = Request("%s%s" % (baseurl, url), headers=headers)
        try:
            req.data = urlencode(data).encode('utf-8') # Python 3
        except:
            try:
                req.add_data(urlencode(data)) # Python 2
            except:
                pass

        # Proxy support
        if self.proxy_url:
            if self.proxy_user:
                proxy = ProxyHandler({'https': 'https://%s:%s@%s' % (self.proxy_user,
                                                                     self.proxy_password,
                                                                     self.proxy_url)})
                auth = HTTPBasicAuthHandler()
                opener = build_opener(proxy, auth, HTTPHandler)
            else:
                handler = ProxyHandler({'https': self.proxy_url})
                opener = build_opener(handler)
        else:
            opener = build_opener()
        resp = opener.open(req)
        charset = resp.info().get('charset', 'utf-8')
        return json.loads(resp.read().decode(charset)) 
開發者ID:gglockner,項目名稱:teslajson,代碼行數:31,代碼來源:teslajson.py

示例4: get

# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPBasicAuthHandler [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) 
開發者ID:naparuba,項目名稱:opsbro,代碼行數:36,代碼來源:httpclient.py

示例5: GetProxiedOpener

# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPBasicAuthHandler [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 ----------------------------------------------- 
開發者ID:TimRivoli,項目名稱:Stock-Price-Trade-Analyzer,代碼行數:28,代碼來源:PriceTradeAnalyzer.py

示例6: get_wsdls

# 需要導入模塊: from urllib import request [as 別名]
# 或者: from urllib.request import HTTPBasicAuthHandler [as 別名]
def get_wsdls(hostname, username='admin', password='admin', verify=False,
              timeout=90, port=443):
    """Returns the set of all available WSDLs on this server

    Used for providing introspection into the available namespaces and WSDLs
    dynamically (e.g. when using iPython)

    @param hostname: The IP address or hostname of the BIGIP.
    @param username: The admin username on the BIGIP.
    @param password: The admin password on the BIGIP.
    @param verify: When True, performs SSL certificate validation in
        Python / urllib2 versions that support it (v2.7.9 and newer)
    @param timeout: The time to wait (in seconds) before timing out the connection
        to the URL
    """
    url = 'https://%s:%s/iControl/iControlPortal.cgi' % (hostname, port)
    regex = re.compile(r'/iControl/iControlPortal.cgi\?WSDL=([^"]+)"')

    auth_handler = HTTPBasicAuthHandler()
    # 10.1.0 has a realm of "BIG-IP"
    auth_handler.add_password(uri='https://%s:%s/' % (hostname, port),
                              user=username, passwd=password, realm="BIG-IP")
    # 11.3.0 has a realm of "BIG-\IP". I'm not sure exactly when it changed.
    auth_handler.add_password(uri='https://%s:%s/' % (hostname, port),
                              user=username, passwd=password, realm="BIG\-IP")
    if verify:
        opener = build_opener(auth_handler)
    else:
        opener = build_opener(auth_handler, HTTPSHandlerNoVerify)
    try:
        result = opener.open(url, timeout=timeout)
    except URLError as e:
        raise ConnectionError(str(e))

    wsdls = {}
    for line in result.readlines():
        result = regex.search(line)
        if result:
            namespace, rest = result.groups()[0].split(".", 1)
            if namespace not in wsdls:
                wsdls[namespace] = []
            wsdls[namespace].append(rest)
    return wsdls 
開發者ID:F5Networks,項目名稱:bigsuds,代碼行數:45,代碼來源:bigsuds.py


注:本文中的urllib.request.HTTPBasicAuthHandler方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。