本文整理汇总了Python中requests.packages.urllib3.disable_warnings函数的典型用法代码示例。如果您正苦于以下问题:Python disable_warnings函数的具体用法?Python disable_warnings怎么用?Python disable_warnings使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了disable_warnings函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, config):
"""
Initialization is responsible for fetching service instance objects for each vCenter instance
pyvmomi has some security checks enabled by default from python 2.7.9 onward to connect to vCenter.
"""
# Holds all the VMs' instanceuuid that are discovered for each of the vCenter. Going ahead it would hold all the
# other managed objects of vCenter that would be monitored.
self.mors = {} # Now mars is act as <key,value>. here key is instance UUID and Values is morf Id
self.params = config
global metrics
global counters
metrics = util.parse_metrics()
counters = util.parse_counters()
self.needed_metrics = {}
self.configured_metrics = {}
self.refresh_rates = {}
self.service_instance = ""
for k, v in metrics.items():
self.configured_metrics.update({util.get_counter(k): v})
if sys.version_info > (2, 7, 9) and sys.version_info < (3, 0, 0):
# https://www.python.org/dev/peps/pep-0476/
# Look for 'Opting out' section in this that talks about disabling the certificate verification
# Following line helps to disable globally
ssl._create_default_https_context = ssl._create_unverified_context
# Disabling the security warning message, as the certificate verification is disabled
urllib3.disable_warnings()
try:
service_instance = connect.SmartConnectNoSSL(host=self.params['host'],
user=self.params['username'],
pwd=self.params['password'],
port=int(self.params['port']))
util.sendEvent("Plugin vmware", "Sucessfully connected to vCenter: [" + self.params['host'] + "]", "info")
atexit.register(connect.Disconnect, service_instance)
self.service_instance = service_instance
self._cache_metrics_metadata(self.params['host'])
except KeyError as ke:
util.sendEvent("Plugin vmware: Key Error", "Improper param.json, key missing: [" + str(ke) + "]", "error")
# sys.exit(-1)
except ConnectionError as ce:
util.sendEvent("Plugin vmware: Error connecting to vCenter",
"Could not connect to the specified vCenter host: [" + str(ce) + "]", "critical")
except Exception as se:
util.sendEvent("Plugin vmware: Unknown Error", "[" + str(se) + "]", "critical")
# sys.exit(-1)
except vim.fault.InvalidLogin as il:
util.sendEvent("Plugin vmware: Error logging into vCenter",
"Could not login to the specified vCenter host: [" + str(il) + "]", "critical")
开发者ID:Kumar-Patil,项目名称:meter-plugin-vmware,代码行数:60,代码来源:vmware.py
示例2: __init__
def __init__(self):
urllib3.disable_warnings()
self.header = {'HOST': 'www.zhihu.com', 'Referer': 'https://www.zhihu.com/people/ipreacher/answers',
'USER-AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/55.0.2883.95 Safari/537.36'}
self.session = requests.session()
self.session.get('https://www.zhihu.com/', headers=self.header, verify=False)
开发者ID:zy108830,项目名称:python-demo,代码行数:7,代码来源:4.验证知乎用户信息.py
示例3: patch_urllib3
def patch_urllib3():
try:
# disable the annoying AppenginePlatformWarning's
import urllib3
urllib3.disable_warnings()
except ImportError:
pass
开发者ID:our-city-app,项目名称:gae-plugin-framework,代码行数:7,代码来源:setup_functions.py
示例4: configure_logging
def configure_logging(debug=None, verbose=None):
"""Configure the logging system
Load the logging configuration file and configure the
logging system.
:param debug: allows to enable/disable the console
debug mode
:param verbose: allows to verbose the debug messages
"""
with open(CONF.basic.log_config, 'r') as f:
logging.config.dictConfig(yaml.load(f))
logger = logging.getLogger()
if not debug:
for handler in logger.handlers:
if handler.name == 'console':
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter())
break
if verbose:
logger.setLevel(logging.DEBUG)
if CONF.basic.hide_ssl_warnings:
urllib3.disable_warnings()
CONF.log_opt_values(logging, logging.DEBUG)
开发者ID:AlBartash,项目名称:mcv-consoler,代码行数:28,代码来源:log.py
示例5: sender
def sender(self):
try:
from requests.packages.urllib3 import disable_warnings
disable_warnings()
except:
logger.info('Unable to disable https warnings. Expect some spam if using https nzb providers.')
try:
logger.info('parameters set to %s' % self.params)
logger.info('sending now to %s' % self.sab_url)
sendit = requests.post(self.sab_url, data=self.params, verify=False)
except:
logger.info('Failed to send to client.')
return {'status': False}
else:
sendresponse = sendit.json()
logger.info(sendresponse)
if sendresponse['status'] is True:
queue_params = {'status': True,
'nzo_id': ''.join(sendresponse['nzo_ids']),
'queue': {'mode': 'queue',
'search': ''.join(sendresponse['nzo_ids']),
'output': 'json',
'apikey': mylar.CONFIG.SAB_APIKEY}}
else:
queue_params = {'status': False}
return queue_params
开发者ID:DarkSir23,项目名称:mylar,代码行数:29,代码来源:sabnzbd.py
示例6: main
def main():
from requests.packages import urllib3
urllib3.disable_warnings()
parser = build_parser()
args = parser.parse_args()
plugins = []
try:
for plugin_name in args.plugins:
cl = import_class(plugin_name)
plugins.append(cl())
nocmd = None
if args.nocmd is not None:
cl = import_class(args.nocmd)
nocmd = cl()
except Exception as e:
parser.error(e.message)
tg = TGBot(args.token, plugins=plugins, no_command=nocmd, db_url=args.db_url)
if args.list:
tg.print_commands()
return
if args.token is None:
parser.error('--token is required')
if args.webhook is None:
tg.run(polling_time=args.polling)
else:
tg.run_web(args.webhook[0], host='0.0.0.0', port=int(args.webhook[1]))
开发者ID:pmpfl,项目名称:tgbotplug,代码行数:34,代码来源:__main__.py
示例7: __init__
def __init__(self, client_id=None, secret=None):
"""
知乎客户端,这是获取所有类的入口。
:param str|unicode client_id: 客户端 ID。
:param str|unicode secret: 客户端 ID 对应的 SECRET KEY。
:rtype: :class:`.ZhihuClient`
"""
self._session = requests.session()
# remove SSL Verify
self._session.verify = False
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Add auto retry for session
self._session.mount('http://', ADAPTER_WITH_RETRY)
self._session.mount('https://', ADAPTER_WITH_RETRY)
# client_id and secret shouldn't have default value
# after zhihu open api
self._client_id = client_id or CLIENT_ID
self._secret = secret or APP_SECRET
self._login_auth = BeforeLoginAuth(self._client_id)
self._token = None
开发者ID:EleVenPerfect,项目名称:OTHERS,代码行数:25,代码来源:client.py
示例8: validate
def validate(self):
"""Run validation using HTTP requests against validation host
Using rules provided by spec, perform requests against validation host
for each rule. Request response is verified to match the spec respsonse
rule. This will yield either a :py:cls:`ValidationPass` or
:py:cls:`ValidationFail` response.
"""
session = Session()
if not self.verify and hasattr(urllib3, 'disable_warnings'):
urllib3.disable_warnings()
for rule in self.spec.get_rules():
req = rule.get_request(self.host, self.port)
if self.debug:
pprint.pprint(req.__dict__)
try:
resp = session.send(req.prepare(), allow_redirects=False,
verify=self.verify)
if self.debug:
pprint.pprint(resp.__dict__)
if rule.matches(resp):
yield ValidationPass(rule=rule, request=req, response=resp)
except (ConnectionError, SSLError) as exc:
# No response yet
yield ValidationFail(rule=rule, request=req, response=None,
error=exc)
except ValidationError as exc:
# Response received, validation error
yield ValidationFail(rule=rule, request=req, response=resp,
error=exc)
开发者ID:agjohnson,项目名称:validatehttp,代码行数:30,代码来源:validate.py
示例9: download
def download(self):
"""
download the NXDL definitions described by ``ref``
"""
_msg = u'disabling warnings about GitHub self-signed https certificates'
#requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
disable_warnings(InsecureRequestWarning)
creds = get_BasicAuth_credentials()
content = None
for _retry in range(GITHUB_RETRY_COUNT): # noqa
try:
if creds is None:
content = requests.get(self.zip_url, verify=False)
else:
content = requests.get(self.zip_url,
auth=(creds['user'], creds['password']),
verify=False,
)
except requests.exceptions.ConnectionError as _exc:
_msg = 'ConnectionError from ' + self.zip_url
_msg += '\n' + str(_exc)
raise IOError(_msg)
else:
break
return content
开发者ID:prjemian,项目名称:punx,代码行数:27,代码来源:github_handler.py
示例10: __init__
def __init__(self, address, **kwargs):
"""
explain me ; )
"""
utils.validate_uri(address)
# TODO: update me with a config file entry need to update to get the version from docker and use that.
self.API_VERSION = DOCKER_API_VERSION
self.url = urlparse(address)
if self.url.scheme == 'https':
# TODO: Need to allow for ca to be passed if not disable warnings.
urllib3.disable_warnings()
for cert_name_type in ('ca', 'cert', 'key'):
cert_path = utils.validate_path(os.path.join(kwargs['ssl_cert_path'], "{0}.pem".format(cert_name_type))) \
if 'ssl_cert_path' in kwargs and kwargs['ssl_cert_path'] else None
setattr(self, 'SSL_{0}_PATH'.format(cert_name_type.upper()), cert_path)
self.SSL_VERIFY = kwargs['verify'] if 'verify' in kwargs and isinstance(kwargs['verify'], bool) else True
if not self.SSL_VERIFY:
self.SSL_CA_PATH = None
client_certs = (self.SSL_CERT_PATH, self.SSL_KEY_PATH) if self.SSL_KEY_PATH and self.SSL_CERT_PATH else None
tls_config = docker.tls.TLSConfig(client_cert=client_certs, ca_cert=self.SSL_CA_PATH, verify=self.SSL_VERIFY)
self._client_session = docker.Client(self.url.geturl(), tls=tls_config, timeout=DOCKER_DEFAULT_TIMEOUT, version=self.API_VERSION)
else:
self._client_session = docker.Client(self.url.geturl(), timeout=DOCKER_DEFAULT_TIMEOUT, version=self.API_VERSION)
self._docker_info = self._client_session.version()
self._injector = None
开发者ID:HasAusten,项目名称:freight_forwarder,代码行数:33,代码来源:container_ship.py
示例11: configure_logging
def configure_logging(log_config=None, debug=None, forward_stdout=None,
hide_ssl_warnings=None):
"""Configure the logging
Loading logging configuration file which is defined in the general
configuration file and configure the logging system.
Setting the level of console handler to DEBUG mode if debug option is set
as True.
Wrap the stdout stream by StdoutLogger.
"""
if log_config is None:
log_config = CONF.migrate.log_config
if debug is None:
debug = CONF.migrate.debug
if forward_stdout is None:
forward_stdout = CONF.migrate.forward_stdout
if hide_ssl_warnings is None:
hide_ssl_warnings = CONF.migrate.hide_ssl_warnings
with open(log_config, 'r') as f:
config.dictConfig(yaml.load(f))
if debug:
logger = logging.getLogger('cloudferry')
for handler in logger.handlers:
if handler.name == 'console':
handler.setLevel(logging.DEBUG)
if forward_stdout:
sys.stdout = StdoutLogger()
if hide_ssl_warnings:
urllib3.disable_warnings()
开发者ID:JabarAli,项目名称:CloudFerry,代码行数:30,代码来源:log.py
示例12: disable_warnings
def disable_warnings(cls, debug):
failures = 0
exmsg = ''
try:
import requests.packages.urllib3 as ul3
if debug:
pdbg("Using requests.packages.urllib3 to disable warnings")
#ul3.disable_warnings(ul3.exceptions.InsecureRequestWarning)
#ul3.disable_warnings(ul3.exceptions.InsecurePlatformWarning)
ul3.disable_warnings()
except Exception as ex:
failures += 1
exmsg += formatex(ex) + '-' * 64 + '\n'
# i don't know why under Ubuntu, 'pip install requests'
# doesn't install the requests.packages.* packages
try:
import urllib3 as ul3
if debug:
pdbg("Using urllib3 to disable warnings")
ul3.disable_warnings()
except Exception as ex:
failures += 1
exmsg += formatex(ex)
if failures >= 2:
perr("Failed to disable warnings for Urllib3.\n"
"Possibly the requests library is out of date?\n"
"You can upgrade it by running '{}'.\nExceptions:\n{}".format(
const.PipUpgradeCommand, exmsg))
开发者ID:beebuu,项目名称:bypy,代码行数:30,代码来源:requester.py
示例13: _get_pool_manager
def _get_pool_manager(verify, cert_file, key_file):
global _pool_manager
default_pool_args = dict(maxsize=32,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=_default_certs,
headers=_default_headers,
timeout=_default_timeout)
if cert_file is None and verify is None and 'DX_CA_CERT' not in os.environ:
with _pool_mutex:
if _pool_manager is None:
if 'HTTPS_PROXY' in os.environ:
proxy_params = _get_proxy_info(os.environ['HTTPS_PROXY'])
default_pool_args.update(proxy_params)
_pool_manager = urllib3.ProxyManager(**default_pool_args)
else:
_pool_manager = urllib3.PoolManager(**default_pool_args)
return _pool_manager
else:
# This is the uncommon case, normally, we want to cache the pool
# manager.
pool_args = dict(default_pool_args,
cert_file=cert_file,
key_file=key_file,
ca_certs=verify or os.environ.get('DX_CA_CERT') or requests.certs.where())
if verify is False or os.environ.get('DX_CA_CERT') == 'NOVERIFY':
pool_args.update(cert_reqs=ssl.CERT_NONE, ca_certs=None)
urllib3.disable_warnings()
if 'HTTPS_PROXY' in os.environ:
proxy_params = _get_proxy_info(os.environ['HTTPS_PROXY'])
pool_args.update(proxy_params)
return urllib3.ProxyManager(**pool_args)
else:
return urllib3.PoolManager(**pool_args)
开发者ID:storozhilov,项目名称:dx-toolkit,代码行数:33,代码来源:__init__.py
示例14: leancloud_init
def leancloud_init():
'''
leancloud初始化
:return:
'''
urllib3.disable_warnings()
leancloud.init('lXyQBue2G2I80NX9OIFY7TRk', 'NkLOGPRHeVrFdJOQiDIGVGJ7')
开发者ID:Namitor,项目名称:CurtainProject,代码行数:7,代码来源:leancloud_manager.py
示例15: main
def main(filename):
disable_warnings()
if not os.path.isfile(os.path.realpath(filename)):
sys.stderr.write("File %s not found.\n" % filename)
sys.exit(1)
basename = os.path.splitext(filename)[0]
response = get_subtitleinfo(filename)
sys.stdout.write("Requesting subtitle file...\n")
subtitles = set([])
for count in xrange(len(response.json())):
if count != 0:
_basename = "%s-alt.%s" % (basename, count)
else:
_basename = "%s.%s" % (basename, count)
for fileinfo in response.json()[count]['Files']:
url = fileinfo['Link']
ext = fileinfo['Ext']
_response = requests.get(url, verify=False)
filename = "%s.%s" % (_basename, ext)
if _response.ok and _response.text not in subtitles:
subtitles.add(_response.text)
fobj = open(filename, 'w')
fobj.write(_response.text.encode("UTF8"))
fobj.close()
开发者ID:xiaket,项目名称:shooter_client,代码行数:27,代码来源:shooter_client.py
示例16: __init__
def __init__(self, api_key):
self.api_key = base64.encodestring('%s:' % api_key).replace('\n', '')
self.user_agent = "SalesMonitoringAgent"
self.headers = {'Authorization': "Basic %s" % self.api_key }
self.headers['Content-type'] = 'application/json'
self.headers['Accept'] = 'application/json'
urllib3.disable_warnings()
开发者ID:SpoofyRoot,项目名称:AlertLogic,代码行数:7,代码来源:ThreatManager.py
示例17: _suppress_urllib3_error
def _suppress_urllib3_error(self):
try:
# Try to suppress user warnings
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from requests.packages.urllib3 import disable_warnings
disable_warnings(InsecureRequestWarning)
except:
pass
开发者ID:01org,项目名称:intelRSD,代码行数:8,代码来源:api_caller.py
示例18: main
def main():
urllib3.disable_warnings()
path, url = sys.argv[1:]
with open(os.path.expanduser(path)) as auth_source:
username, password = auth_source.read().strip().split(':')
response = requests.get(url, auth=HTTPBasicAuth(username, password))
if response.status_code != 200 or not response.text.startswith('<SUCCESS CODE="20'):
print response.text
开发者ID:cjw296,项目名称:ddns,代码行数:8,代码来源:client.py
示例19: requests_get_mock
def requests_get_mock(*args, **kwargs):
self.assertEquals(kwargs.get('timeout'), 5)
with requests.sessions.Session() as session:
from requests.packages import urllib3
urllib3.disable_warnings()
return requests_mock.create_response(
session.request('GET', args[0]), json={})
开发者ID:beylsp,项目名称:appletea,代码行数:8,代码来源:test_api.py
示例20: init
def init(self, url=None, username=None, password=None):
self.url = url
self.username = username
self.password = password
self.auth = HTTPBasicAuth(username, password)
self.content_type = {'Content-Type': 'application/xml'}
self.accept_header = {'Accept': 'application/xml'}
disable_warnings()
开发者ID:emitrom,项目名称:integra-sdk-python,代码行数:8,代码来源:RestTemplate.py
注:本文中的requests.packages.urllib3.disable_warnings函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论