コード例 #1
0
ファイル: context.py プロジェクト: google/upvote
    def _UnwrapResponse(cls, response):
        """Checks the status code and parses the contents of a response.

    Args:
      response: HttpResponse from Bit9.

    Returns:
      JSON encoded text from the response.

    Raises:
      NotFoundError: If the response returned a 404 (object not found).
      RequestError: The response had a failure status code.
    """
        if response.status_code == six.moves.http_client.NOT_FOUND:
            raise excs.NotFoundError('Object in request cannot be found')
        # All 300s and 100s should be resolved by the requests library.
        elif response.status_code >= 400:
            raise excs.RequestError('{} Error: {}'.format(
                response.status_code, response.text))
        elif response.text:
            try:
                return json.loads(response.text, object_hook=UnicodeToAscii)
            except:
                raise excs.RequestError(
                    'Error getting JSON from response: {}'.format(
                        response.text))
        else:
            raise excs.RequestError('No content')
コード例 #2
0
ファイル: context.py プロジェクト: google/upvote
    def ExecuteRequest(self,
                       method,
                       api_route=None,
                       query_args=None,
                       data=None):
        """Execute an API request using the current API context."""
        if method not in constants.METHOD.SET_ALL:
            raise ValueError('Invalid method: {}'.format(method))

        url = self._GetApiUrl(api_route, query_args)

        if data is None:
            logging.info('API %s: %s', method, url)
        else:
            logging.info('API %s: %s (data: %s)', method, url, data)

        try:
            response = requests.request(method,
                                        url,
                                        headers=self._GetApiHeaders(),
                                        json=data,
                                        verify=True,
                                        timeout=self.timeout)
        except requests.RequestException as e:
            raise excs.RequestError('Error performing {} {}: {}'.format(
                method, url, e))
        else:
            return self._UnwrapResponse(response)