Call the DISQUS API and return the json response.
        URLError is raised when the request failed.
        DisqusException is raised when the query didn't succeed.
512158
def call(self, method, **params):
        
        url = self.api_url % method
        request = self._get_request(url, self.METHODS[method], **params)
        try:
            response = urlopen(request)
        except URLError:
            raise
        else:
            response_json = json.loads(response.read())
            if not response_json['succeeded']:
                raise DisqusException(response_json['message'])
            return response_json['message']
172169
def json_exception(context, request):
    """"""
    request.response.status = context.code
    return {'error': context._status, 'messages': context.message}
825433
def _http_call(self, url, method, data=None, **kwargs):
        
        response = self._http_response(url, method, data=data, **kwargs)
        if not response.content:
            return {}

        return response.json()
434744
def json(self, **kwargs):
        
        try:
            return super(ScraperResponse, self).json(**kwargs)
        except ValueError as ve:
            raise ParseException(ve)
833399
def _process_response(response):
        
        if response.status_code == 404:
            raise Trovebox404Error("HTTP Error %d: %s" %
                                   (response.status_code, response.reason))
        try:
            json_response = response.json()
            code = json_response["code"]
            message = json_response["message"]
        except (ValueError, KeyError):
            # Response wasn't Trovebox JSON - check the HTTP status code
            if 200 <= response.status_code < 300:
                # Status code was valid, so just reraise the exception
                raise
            else:
                raise TroveboxError("HTTP Error %d: %s" %
                                    (response.status_code, response.reason))

        if 200 <= code < 300:
            return json_response
        elif (code == DUPLICATE_RESPONSE["code"] and
               DUPLICATE_RESPONSE["message"] in message):
            raise TroveboxDuplicateError("Code %d: %s" % (code, message))
        else:
            raise TroveboxError("Code %d: %s" % (code, message))
69068
def handle_error(self, error, response):
        
        query_params = {"error": error.error}

        query = urlencode(query_params)

        location = "%s?%s" % (self.client.redirect_uri, query)

        response.status_code = 302
        response.body = ""
        response.add_header("Location", location)

        return response
967885
def result_or_error(response):
    
    data = response.json()
    result = data.get('result')
    if result is not None:
        return result
    raise exceptions.ApiError(response, data)
91152
async def get_json(self, url, timeout=30, astext=False, exceptions=False):
        """"""
        try:
            with async_timeout.timeout(timeout):
                res = await self._aio_session.get(url)
                if res.status != 200:
                    _LOGGER.error("QSUSB returned %s [%s]", res.status, url)
                    return None
                res_text = await res.text()
        except (aiohttp.client_exceptions.ClientError,
                asyncio.TimeoutError) as exc:
            if exceptions:
                raise exc
            return None

        if astext:
            return res_text

        try:
            return json.loads(res_text)
        except json.decoder.JSONDecodeError:
            if res_text.strip(" ") == "":
                return None
            _LOGGER.error("Could not decode %s [%s]", res_text, url)
1322088
def json_request_response(f):
    
    @wraps(f)
    def wrapper(*args, **kwargs):
        response = f(*args, **kwargs)
        response.raise_for_status()
        return json.loads(response.content.decode('utf-8'))

    API_FUNCTIONS[f.__name__] = f
    return wrapper
555424
def render_to_json(response, request=None, **kwargs):
    
    # determine the status code
    if hasattr(response, 'status_code'):
        status_code = response.status_code
    elif issubclass(type(response), Http404):
        status_code = 404
    elif issubclass(type(response), Exception):
        status_code = 500
        logger.exception(str(response), extra={'request': request})
        
        if settings.DEBUG:
            import sys
            reporter = ExceptionReporter(None, *sys.exc_info())
            text = reporter.get_traceback_text()
            response = HttpResponseServerError(text, content_type='text/plain')
        else:
            response = HttpResponseServerError("An error occured while processing an AJAX request.", content_type='text/plain')
    else:
        status_code = 200

    # creating main structure
    data = {
        'status': status_code,
        'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'),
        'content': response
    }

    return JSONResponse(data, **kwargs)
640125
def unauthorized(cls, errors=None):
        
        if cls.expose_status:  # pragma: no cover
            cls.response.content_type = 'application/json'
            cls.response._status_line = '401 Unauthorized'

        return cls(401, errors=errors).to_json
649227
def _do_request(self, url, params=None, data=None, headers=None):
        

        if not headers:
            headers = {'content-type': 'application/json'}

        try:
            response = requests.get(
                url, params=params, data=data, headers=headers)
        except:
            return None

        if response.status_code == 200:
            return response
1373325
def request(self, url):
        
        self.logger.debug('url:\n' + url)
        try:
            response = urlopen(url)
            return json.loads(response.read().decode('utf-8'))
        except URLError:
            self.logger.info('Server connection problem')
        except Exception:
            self.logger.info('Server format problem')
61061
def call(self, default_response=None, **query_params):
        
        query_url = self.get_query_url(**query_params)
        return self._perform_call(query_url, default_response)
993310
def handle_error(r, expected_code):
    
    code = r.status_code
    if code != expected_code:
        info = 'API response status code {}'.format(code)
        try:
            if 'detail' in r.json():
                info = info + ": {}".format(r.json()['detail'])
            elif 'metadata' in r.json():
                info = info + ": {}".format(r.json()['metadata'])
        except json.decoder.JSONDecodeError:
            info = info + ":\n{}".format(r.content)
        raise Exception(info)
593662
def get_json_results(self, response):
        '''
        
        '''
        try:
            # return the proper JSON object, or error code if request didn't go through.
            self.most_recent_json = response.json()
            json_results = response.json()
            if response.status_code in [401, 403]: #401 is invalid key, 403 is out of monthly quota.
                raise PyMsCognitiveWebSearchException("CODE {code}: {message}".format(code=response.status_code,message=json_results["message"]) )
            elif response.status_code in [429]: #429 means try again in x seconds.
                message = json_results['message']
                try:
                    # extract time out seconds from response
                    timeout = int(re.search('in (.+?) seconds', message).group(1)) + 1
                    print ("CODE 429, sleeping for {timeout} seconds").format(timeout=str(timeout))
                    time.sleep(timeout)
                except (AttributeError, ValueError) as e:
                    if not self.silent_fail:
                        raise PyMsCognitiveWebSearchException("CODE 429. Failed to auto-sleep: {message}".format(code=response.status_code,message=json_results["message"]) )
                    else:
                        print ("CODE 429. Failed to auto-sleep: {message}. Trying again in 5 seconds.".format(code=response.status_code,message=json_results["message"]))
                        time.sleep(5)
        except ValueError as vE:
            if not self.silent_fail:
                raise PyMsCognitiveWebSearchException("Request returned with code %s, error msg: %s" % (r.status_code, r.text))
            else:
                print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text))
                time.sleep(5)
        return json_results
1029555
def execute(self, url, params):
        
        response = requests.get(url, params=params, **self.config.requests_kwargs)

        if 520 <= response.status_code < 530:
            if self.config.handler52x:
                return self.config.handler52x(response, self, url, params)

        response.raise_for_status()

        if not self.config.response_type:
            return response.json()
        else:
            return response.text