Python urllib3.exceptions() Examples

The following are 23 code examples of urllib3.exceptions(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module urllib3 , or try the search function .
Example #1
Source File: requests_wrapper.py    From py-ipfs-http-client with MIT License 6 votes vote down vote up
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 
Example #2
Source File: api.py    From python-wink with MIT License 6 votes vote down vote up
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 
Example #3
Source File: api.py    From python-wink with MIT License 6 votes vote down vote up
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 
Example #4
Source File: urllib3.py    From google-auth-library-python with Apache License 2.0 5 votes vote down vote up
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) 
Example #5
Source File: urllib3.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
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) 
Example #6
Source File: api.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #7
Source File: api.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #8
Source File: api.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #9
Source File: api.py    From python-wink with MIT License 5 votes vote down vote up
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 
Example #10
Source File: api.py    From python-wink with MIT License 5 votes vote down vote up
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 
Example #11
Source File: api.py    From python-wink with MIT License 5 votes vote down vote up
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 
Example #12
Source File: urllib3.py    From luci-py with Apache License 2.0 5 votes vote down vote up
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) 
Example #13
Source File: urllib3.py    From luci-py with Apache License 2.0 5 votes vote down vote up
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) 
Example #14
Source File: urllib3.py    From luci-py with Apache License 2.0 5 votes vote down vote up
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) 
Example #15
Source File: urllib3.py    From luci-py with Apache License 2.0 5 votes vote down vote up
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) 
Example #16
Source File: urllib3.py    From luci-py with Apache License 2.0 5 votes vote down vote up
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) 
Example #17
Source File: urllib3.py    From alfred-gmail with MIT License 5 votes vote down vote up
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) 
Example #18
Source File: api.py    From python-wink with MIT License 4 votes vote down vote up
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) 
Example #19
Source File: api.py    From python-wink with MIT License 4 votes vote down vote up
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) 
Example #20
Source File: http.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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 
Example #21
Source File: api.py    From jarvis with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #22
Source File: api.py    From jarvis with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #23
Source File: urllib3.py    From google-auth-library-python with Apache License 2.0 4 votes vote down vote up
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