本文整理汇总了Python中urllib3.exceptions方法的典型用法代码示例。如果您正苦于以下问题:Python urllib3.exceptions方法的具体用法?Python urllib3.exceptions怎么用?Python urllib3.exceptions使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类urllib3
的用法示例。
在下文中一共展示了urllib3.exceptions方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _new_conn
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def _new_conn(self):
extra_kw = {
"family": self.family
}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['socket_options'] = self.socket_options
try:
dns_host = getattr(self, "_dns_host", self.host)
conn = create_connection(
(dns_host, self.port), self.timeout, **extra_kw)
except socket.timeout:
raise urllib3.exceptions.ConnectTimeoutError(
self, "Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout))
except OSError as e:
raise urllib3.exceptions.NewConnectionError(
self, "Failed to establish a new connection: %s" % e)
return conn
示例2: piggy_bank_deposit
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def piggy_bank_deposit(self, device, _json):
"""
Args:
device (WinkPorkfolioBalanceSensor): The piggy bank device to deposit to/withdrawal from.
_json (String): The JSON string to perform the deposit/withdrawal.
Returns:
response_json (Dict): The API's response in dictionary format
"""
url_string = "{}/{}s/{}/deposits".format(self.BASE_URL,
device.object_type(),
device.object_id())
try:
arequest = requests.post(url_string,
data=json.dumps(_json),
headers=API_HEADERS)
response_json = arequest.json()
return response_json
except requests.exceptions.RequestException:
return None
示例3: post_session
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def post_session():
"""
This endpoint appears to be required in order to keep pubnub updates flowing for some user.
This just posts a random nonce to the /users/me/session endpoint and returns the result.
"""
url_string = "{}/users/me/session".format(WinkApiInterface.BASE_URL)
nonce = ''.join([str(random.randint(0, 9)) for i in range(9)])
_json = {"nonce": str(nonce)}
try:
arequest = requests.post(url_string,
data=json.dumps(_json),
headers=API_HEADERS)
response_json = arequest.json()
return response_json
except requests.exceptions.RequestException:
return None
示例4: __call__
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def __call__(
self, url, method="GET", body=None, headers=None, timeout=None, **kwargs
):
"""Make an HTTP request using urllib3.
Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping[str, str]): Request headers.
timeout (Optional[int]): The number of seconds to wait for a
response from the server. If not specified or if None, the
urllib3 default timeout will be used.
kwargs: Additional arguments passed throught to the underlying
urllib3 :meth:`urlopen` method.
Returns:
google.auth.transport.Response: The HTTP response.
Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
# urllib3 uses a sentinel default value for timeout, so only set it if
# specified.
if timeout is not None:
kwargs["timeout"] = timeout
try:
_LOGGER.debug("Making request: %s %s", method, url)
response = self.http.request(
method, url, body=body, headers=headers, **kwargs
)
return _Response(response)
except urllib3.exceptions.HTTPError as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)
示例5: __call__
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def __call__(self, url, method='GET', body=None, headers=None,
timeout=None, **kwargs):
"""Make an HTTP request using urllib3.
Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping[str, str]): Request headers.
timeout (Optional[int]): The number of seconds to wait for a
response from the server. If not specified or if None, the
urllib3 default timeout will be used.
kwargs: Additional arguments passed throught to the underlying
urllib3 :meth:`urlopen` method.
Returns:
google.auth.transport.Response: The HTTP response.
Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
# urllib3 uses a sentinel default value for timeout, so only set it if
# specified.
if timeout is not None:
kwargs['timeout'] = timeout
try:
_LOGGER.debug('Making request: %s %s', method, url)
response = self.http.request(
method, url, body=body, headers=headers, **kwargs)
return _Response(response)
except urllib3.exceptions.HTTPError as caught_exc:
new_exc = exceptions.TransportError(caught_exc)
six.raise_from(new_exc, caught_exc)
示例6: update_firmware
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def update_firmware(self, device, id_override=None, type_override=None):
"""
Make a call to the update_firmware endpoint. As far as I know this
is only valid for Wink hubs.
Args:
device (WinkDevice): The device the change is being requested for.
id_override (String, optional): A device ID used to override the
passed in device's ID. Used to make changes on sub-devices.
i.e. Outlet in a Powerstrip. The Parent device's ID.
type_override (String, optional): Used to override the device type
when a device inherits from a device other than WinkDevice.
Returns:
response_json (Dict): The API's response in dictionary format
"""
object_id = id_override or device.object_id()
object_type = type_override or device.object_type()
url_string = "{}/{}s/{}/update_firmware".format(self.BASE_URL,
object_type,
object_id)
try:
arequest = requests.post(url_string,
headers=API_HEADERS)
response_json = arequest.json()
return response_json
except requests.exceptions.RequestException:
return None
示例7: remove_device
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def remove_device(self, device, id_override=None, type_override=None):
"""
Remove a device.
Args:
device (WinkDevice): The device the change is being requested for.
id_override (String, optional): A device ID used to override the
passed in device's ID. Used to make changes on sub-devices.
i.e. Outlet in a Powerstrip. The Parent device's ID.
type_override (String, optional): Used to override the device type
when a device inherits from a device other than WinkDevice.
Returns:
(boolean): True if the device was removed.
"""
object_id = id_override or device.object_id()
object_type = type_override or device.object_type()
url_string = "{}/{}s/{}".format(self.BASE_URL,
object_type,
object_id)
try:
arequest = requests.delete(url_string,
headers=API_HEADERS)
if arequest.status_code == 204:
return True
_LOGGER.error("Failed to remove device. Status code: %s", arequest.status_code)
return False
except requests.exceptions.RequestException:
_LOGGER.error("Failed to remove device.")
return False
示例8: create_lock_key
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def create_lock_key(self, device, new_device_json, id_override=None, type_override=None):
"""
Create a new lock key code.
Args:
device (WinkDevice): The device the change is being requested for.
new_device_json (String): The JSON string required to create the device.
id_override (String, optional): A device ID used to override the
passed in device's ID. Used to make changes on sub-devices.
i.e. Outlet in a Powerstrip. The Parent device's ID.
type_override (String, optional): Used to override the device type
when a device inherits from a device other than WinkDevice.
Returns:
response_json (Dict): The API's response in dictionary format
"""
object_id = id_override or device.object_id()
object_type = type_override or device.object_type()
url_string = "{}/{}s/{}/keys".format(self.BASE_URL,
object_type,
object_id)
try:
arequest = requests.post(url_string,
data=json.dumps(new_device_json),
headers=API_HEADERS)
response_json = arequest.json()
return response_json
except requests.exceptions.RequestException:
return None
示例9: __call__
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def __call__(self, url, method='GET', body=None, headers=None,
timeout=None, **kwargs):
"""Make an HTTP request using urllib3.
Args:
url (str): The URI to be requested.
method (str): The HTTP method to use for the request. Defaults
to 'GET'.
body (bytes): The payload / body in HTTP request.
headers (Mapping[str, str]): Request headers.
timeout (Optional[int]): The number of seconds to wait for a
response from the server. If not specified or if None, the
urllib3 default timeout will be used.
kwargs: Additional arguments passed throught to the underlying
urllib3 :meth:`urlopen` method.
Returns:
google.auth.transport.Response: The HTTP response.
Raises:
google.auth.exceptions.TransportError: If any exception occurred.
"""
# urllib3 uses a sentinel default value for timeout, so only set it if
# specified.
if timeout is not None:
kwargs['timeout'] = timeout
try:
_LOGGER.debug('Making request: %s %s', method, url)
response = self.http.request(
method, url, body=body, headers=headers, **kwargs)
return _Response(response)
except urllib3.exceptions.HTTPError as exc:
raise exceptions.TransportError(exc)
示例10: configure_mtls_channel
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def configure_mtls_channel(self, client_cert_callback=None):
"""Configures mutual TLS channel using the given client_cert_callback or
application default SSL credentials. Returns True if the channel is
mutual TLS and False otherwise. Note that the `http` provided in the
constructor will be overwritten.
Args:
client_cert_callback (Optional[Callable[[], (bytes, bytes)]]):
The optional callback returns the client certificate and private
key bytes both in PEM format.
If the callback is None, application default SSL credentials
will be used.
Returns:
True if the channel is mutual TLS and False otherwise.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS channel
creation failed for any reason.
"""
try:
import OpenSSL
except ImportError as caught_exc:
new_exc = exceptions.MutualTLSChannelError(caught_exc)
six.raise_from(new_exc, caught_exc)
try:
found_cert_key, cert, key = transport._mtls_helper.get_client_cert_and_key(
client_cert_callback
)
if found_cert_key:
self.http = _make_mutual_tls_http(cert, key)
else:
self.http = _make_default_http()
except (
exceptions.ClientCertError,
ImportError,
OpenSSL.crypto.Error,
) as caught_exc:
new_exc = exceptions.MutualTLSChannelError(caught_exc)
six.raise_from(new_exc, caught_exc)
if self._has_user_provided_http:
self._has_user_provided_http = False
warnings.warn(
"`http` provided in the constructor is overwritten", UserWarning
)
return found_cert_key
示例11: get_config
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def get_config(self, current_version=None, keys=None):
"""
Gets configuration from a remote APM Server
:param current_version: version of the current configuration
:param keys: a JSON-serializable dict to identify this instance, e.g.
{
"service": {
"name": "foo",
"environment": "bar"
}
}
:return: a three-tuple of new version, config dictionary and validity in seconds.
Any element of the tuple can be None.
"""
url = self._config_url
data = json_encoder.dumps(keys).encode("utf-8")
headers = self._headers.copy()
headers[b"Content-Type"] = "application/json"
headers.pop(b"Content-Encoding", None) # remove gzip content-encoding header
headers.update(self.auth_headers)
max_age = 300
if current_version:
headers["If-None-Match"] = current_version
try:
response = self.http.urlopen(
"POST", url, body=data, headers=headers, timeout=self._timeout, preload_content=False
)
except (urllib3.exceptions.RequestError, urllib3.exceptions.HTTPError) as e:
logger.debug("HTTP error while fetching remote config: %s", compat.text_type(e))
return current_version, None, max_age
body = response.read()
if "Cache-Control" in response.headers:
try:
max_age = int(next(re.finditer(r"max-age=(\d+)", response.headers["Cache-Control"])).groups()[0])
except StopIteration:
logger.debug("Could not parse Cache-Control header: %s", response.headers["Cache-Control"])
if response.status == 304:
# config is unchanged, return
logger.debug("Configuration unchanged")
return current_version, None, max_age
elif response.status >= 400:
return None, None, max_age
if not body:
logger.debug("APM Server answered with empty body and status code %s", response.status)
return current_version, None, max_age
return response.headers.get("Etag"), json_encoder.loads(body.decode("utf-8")), max_age
示例12: local_set_state
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def local_set_state(self, device, state, id_override=None, type_override=None):
"""
Set device state via local API, and fall back to online API.
Args:
device (WinkDevice): The device the change is being requested for.
state (Dict): The state being requested.
id_override (String, optional): A device ID used to override the
passed in device's ID. Used to make changes on sub-devices.
i.e. Outlet in a Powerstrip. The Parent device's ID.
type_override (String, optional): Used to override the device type
when a device inherits from a device other than WinkDevice.
Returns:
response_json (Dict): The API's response in dictionary format
"""
if ALLOW_LOCAL_CONTROL:
if device.local_id() is not None:
hub = HUBS.get(device.hub_id())
if hub is None or hub["token"] is None:
return self.set_device_state(device, state, id_override, type_override)
else:
return self.set_device_state(device, state, id_override, type_override)
_LOGGER.info("Setting local state")
local_id = id_override or device.local_id().split(".")[0]
object_type = type_override or device.object_type()
LOCAL_API_HEADERS['Authorization'] = "Bearer " + hub["token"]
url_string = "https://{}:8888/{}s/{}".format(hub["ip"],
object_type,
local_id)
try:
arequest = requests.put(url_string,
data=json.dumps(state),
headers=LOCAL_API_HEADERS,
verify=False, timeout=3)
except requests.exceptions.RequestException:
_LOGGER.error("Error sending local control request. Sending request online")
return self.set_device_state(device, state, id_override, type_override)
response_json = arequest.json()
_LOGGER.debug('%s', response_json)
temp_state = device.json_state
for key, value in response_json["data"]["last_reading"].items():
temp_state["last_reading"][key] = value
return temp_state
else:
return self.set_device_state(device, state, id_override, type_override)
示例13: local_get_state
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def local_get_state(self, device, id_override=None, type_override=None):
"""
Get device state via local API, and fall back to online API.
Args:
device (WinkDevice): The device the change is being requested for.
id_override (String, optional): A device ID used to override the
passed in device's ID. Used to make changes on sub-devices.
i.e. Outlet in a Powerstrip. The Parent device's ID.
type_override (String, optional): Used to override the device type
when a device inherits from a device other than WinkDevice.
Returns:
response_json (Dict): The API's response in dictionary format
"""
if ALLOW_LOCAL_CONTROL:
if device.local_id() is not None:
hub = HUBS.get(device.hub_id())
if hub is not None and hub["token"] is not None:
ip = hub["ip"]
access_token = hub["token"]
else:
return self.get_device_state(device, id_override, type_override)
else:
return self.get_device_state(device, id_override, type_override)
_LOGGER.info("Getting local state")
local_id = id_override or device.local_id()
object_type = type_override or device.object_type()
LOCAL_API_HEADERS['Authorization'] = "Bearer " + access_token
url_string = "https://{}:8888/{}s/{}".format(ip,
object_type,
local_id)
try:
arequest = requests.get(url_string,
headers=LOCAL_API_HEADERS,
verify=False, timeout=3)
except requests.exceptions.RequestException:
_LOGGER.error("Error sending local control request. Sending request online")
return self.get_device_state(device, id_override, type_override)
response_json = arequest.json()
_LOGGER.debug('%s', response_json)
temp_state = device.json_state
for key, value in response_json["data"]["last_reading"].items():
temp_state["last_reading"][key] = value
return temp_state
else:
return self.get_device_state(device, id_override, type_override)
示例14: local_set_state
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def local_set_state(self, device, state, id_override=None, type_override=None):
"""
Set device state via local API, and fall back to online API.
Args:
device (WinkDevice): The device the change is being requested for.
state (Dict): The state being requested.
id_override (String, optional): A device ID used to override the
passed in device's ID. Used to make changes on sub-devices.
i.e. Outlet in a Powerstrip. The Parent device's ID.
type_override (String, optional): Used to override the device type
when a device inherits from a device other than WinkDevice.
Returns:
response_json (Dict): The API's response in dictionary format
"""
if ALLOW_LOCAL_CONTROL:
if device.local_id() is not None:
hub = HUBS.get(device.hub_id())
if hub is None:
return self.set_device_state(device, state, id_override, type_override)
else:
return self.set_device_state(device, state, id_override, type_override)
_LOGGER.info("Setting local state")
local_id = id_override or device.local_id().split(".")[0]
object_type = type_override or device.object_type()
LOCAL_API_HEADERS['Authorization'] = "Bearer " + hub["token"]
url_string = "https://{}:8888/{}s/{}".format(hub["ip"],
object_type,
local_id)
try:
arequest = requests.put(url_string,
data=json.dumps(state),
headers=LOCAL_API_HEADERS,
verify=False, timeout=3)
except requests.exceptions.RequestException:
_LOGGER.error("Error sending local control request. Sending request online")
return self.set_device_state(device, state, id_override, type_override)
response_json = arequest.json()
_LOGGER.debug('%s', response_json)
temp_state = device.json_state
for key, value in response_json["data"]["last_reading"].items():
temp_state["last_reading"][key] = value
return temp_state
else:
return self.set_device_state(device, state, id_override, type_override)
示例15: local_get_state
# 需要导入模块: import urllib3 [as 别名]
# 或者: from urllib3 import exceptions [as 别名]
def local_get_state(self, device, id_override=None, type_override=None):
"""
Get device state via local API, and fall back to online API.
Args:
device (WinkDevice): The device the change is being requested for.
id_override (String, optional): A device ID used to override the
passed in device's ID. Used to make changes on sub-devices.
i.e. Outlet in a Powerstrip. The Parent device's ID.
type_override (String, optional): Used to override the device type
when a device inherits from a device other than WinkDevice.
Returns:
response_json (Dict): The API's response in dictionary format
"""
if ALLOW_LOCAL_CONTROL:
if device.local_id() is not None:
hub = HUBS.get(device.hub_id())
if hub is not None:
ip = hub["ip"]
access_token = hub["token"]
else:
return self.get_device_state(device, id_override, type_override)
else:
return self.get_device_state(device, id_override, type_override)
_LOGGER.info("Getting local state")
local_id = id_override or device.local_id()
object_type = type_override or device.object_type()
LOCAL_API_HEADERS['Authorization'] = "Bearer " + access_token
url_string = "https://{}:8888/{}s/{}".format(ip,
object_type,
local_id)
try:
arequest = requests.get(url_string,
headers=LOCAL_API_HEADERS,
verify=False, timeout=3)
except requests.exceptions.RequestException:
_LOGGER.error("Error sending local control request. Sending request online")
return self.get_device_state(device, id_override, type_override)
response_json = arequest.json()
_LOGGER.debug('%s', response_json)
temp_state = device.json_state
for key, value in response_json["data"]["last_reading"].items():
temp_state["last_reading"][key] = value
return temp_state
else:
return self.get_device_state(device, id_override, type_override)