Output the requests response JSON and status code

    :rtype : dict
    :param response: requests response object
    :return: dict containing the JSON response and/or the status code with error string.
966340
def _return_response_and_status_code(response):
    
    if response.status_code == requests.codes.ok:
        return dict(results=response.json(), response_code=response.status_code)
    elif response.status_code == 204:
        return dict(error='You exceeded the public API request rate limit (4 requests of any nature per minute)',
                    response_code=response.status_code)
    elif response.status_code == 403:
        return dict(error='You tried to perform calls to functions for which you require a Private API key.',
                    response_code=response.status_code)
    else:
        return dict(response_code=response.status_code)
503533
def create_response(
        self, data: dict = None, response: requests.Response = None, errors: list = None
    ) -> Response:
        
        status = FAILURE_STATUS if errors else SUCCESS_STATUS
        return Response(
            status=status,
            provider=self.name,
            data=data,
            response=response,
            errors=errors,
        )
90669
def get_output(cls, response: requests.Response) -> str:
        
        output = response.headers['X-Lizzy-Output']  # type: str
        output = output.replace('\\n', '\n')  # unescape new lines
        lines = ('[AGENT] {}'.format(line) for line in output.splitlines())
        return '\n'.join(lines)
459427
def log_print_response(status_code, response, headers=None):
    

    log_msg = '\n<<<<<<<<<<<<<<<<<<<<<< Response <<<<<<<<<<<<<<<<<<\n'
    log_msg += '\t< Response code: {}\n'.format(str(status_code))
    if headers is not None:
        log_msg += '\t< Headers:\n{}\n'.format(json.dumps(dict(headers), sort_keys=True, indent=4))
    try:
        log_msg += '\t< Payload received:\n{}'.format(_get_pretty_body(headers, response))
    except:
        log_msg += '\t< Payload received:\n{}'.format(response)
    logger.debug(log_msg)
954612
def raw_response(json, status)
      json.empty? ? {} : JSON.parse(json, symbolize_names: true)
    rescue StandardError
      { message: json, code: status }
    end
1014695
def _request_process_json_standard(self, response_data):
        
        data = response_data.get('data', {}).get(self.request_entity, [])
        status = response_data.get('status', 'Failure')
        return data, status
541250
def json_to_response(self, action=None, json_status=None, success_url=None,
                         json_data=None, **response_kwargs):
        
        data = {
            "status": self.get_status(json_status),
            "action": self.get_action(action),
            "extra_data": self.get_json_data(json_data or {})
        }

        if self.action == AjaxResponseAction.REDIRECT:
            data["action_url"] = success_url or self.get_success_url()
        return JsonResponse(data, **response_kwargs)
560980
def process_response(self, response):
        
        if response.status_code != 200:
            raise TwilioException('Unable to fetch page', response)

        return json.loads(response.text)
73590
def generate_response(self, response):
        
        if not response:
            return self.__serializer__.dump({})

        return self.__serializer__.dump(response.to_dict())
801494
def jsonify(self, status_code=None, message=None, headers=None):
        
        if status_code is None:
            status_code = self.status_code
        if message is None:
            message = self.message
        if headers is None:
            headers = self.headers
        response = flask.jsonify({
            'status_code': status_code,
            'error': repr(self),
            'message': message,
        })
        if status_code is not None:
            response.status_code = status_code
        if headers is not None:
            response.headers = headers
        return response
42798
def check_api_response(self, response):
        
        # check response
        if response.status_code == 200:
            return True
        elif response.status_code >= 400:
            logging.error(
                "{}: {} - {} - URL: {}".format(
                    response.status_code,
                    response.reason,
                    response.json().get("error"),
                    response.request.url,
                )
            )
            return False, response.status_code
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)
408872
def output(self, response, accepts):
		
		graph = self.get_graph(response)
		if graph is not None:
			# decide the format
			mimetype, format = self.format_selector.decide(accepts, graph.context_aware)

			# requested content couldn't find anything
			if mimetype is None:
				return self.make_406_response()

			# explicitly mark text mimetypes as utf-8
			if 'text' in mimetype:
				mimetype = mimetype + '; charset=utf-8'

			# format the new response
			serialized = graph.serialize(format=format)
			response = self.make_new_response(response, mimetype, serialized)
			return response
		else:
			return response
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
166734
def response_shim(body, status)
      resp, err_msg = parsed_response(body)

      { response: resp,
        status:   { result:  status == 200 ? 'OK' : 'ERROR',
                    message: err_msg,
                    code:    status } }.to_json
    end
620074
def jd(api_response):
        
        try:
            # attempt to print the cgx_content. should always be a Dict if it exists.
            print(json.dumps(api_response.cgx_content, indent=4))
        except (TypeError, ValueError, AttributeError):
            # cgx_content did not exist, or was not JSON serializable. Try pretty printing the base obj.
            try:
                print(json.dumps(api_response, indent=4))
            except (TypeError, ValueError, AttributeError):
                # Same issue, just raw print the passed data. Let any exceptions happen here.
                print(api_response)
        return
398820
def json_error_response(error, response, status_code=400):
    
    msg = {"error": error.error, "error_description": error.explanation}

    response.status_code = status_code
    response.add_header("Content-Type", "application/json")
    response.body = json.dumps(msg)

    return response