Return friendly response from API based on response code.
559970
def status_message(self):
        

        msg = None
        if self.last_ddns_response in response_messages.keys():
            return response_messages.get(self.last_ddns_response)

        if 'good' in self.last_ddns_response:
            ip = re.search(r'(\d{1,3}\.?){4}', self.last_ddns_response).group()
            msg = "SUCCESS: DNS hostname IP (%s) successfully updated." % ip
        elif 'nochg' in self.last_ddns_response:
            ip = re.search(r'(\d{1,3}\.?){4}', self.last_ddns_response).group()
            msg = "SUCCESS: IP address (%s) is up to date, nothing was changed. " \
                  "Additional 'nochg' updates may be considered abusive." % ip
        else:
            msg = "ERROR: Ooops! Something went wrong !!!"

        return msg
483435
def _api_response(response):
    '''
    
    '''
    if response.status_code == 404:
        __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
        raise CommandExecutionError('Element doesn\'t exists')
    if response.status_code == 401:
        __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
        raise CommandExecutionError('Bad username or password')
    elif response.status_code == 200 or response.status_code == 500:
        try:
            data = salt.utils.json.loads(response.content)
            if data['exit_code'] != 'SUCCESS':
                __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
                raise CommandExecutionError(data['message'])
            return data
        except ValueError:
            __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
            raise CommandExecutionError('The server returned no data')
    else:
        response.raise_for_status()
1106077
def _handle_response(self, response):
        
        if not str(response.status_code).startswith('2'):
            raise BinanceAPIException(response)
        try:
            return response.json()
        except ValueError:
            raise BinanceRequestException('Invalid Response: %s' % response.text)
139901
def _api_action(url, req, data=None):
    """"""
    requisite_headers = {'Accept': 'application/json',
                         'Content-Type': 'application/json'}
    auth = (user, token)

    if req == "GET":
        response = requests.get(url, headers=requisite_headers, auth=auth)
    elif req == "PUT":
        response = requests.put(url, headers=requisite_headers, auth=auth,
                                data=data)
    elif req == "POST":
        response = requests.post(url, headers=requisite_headers, auth=auth,
                                 data=data)
    elif req == "DELETE":
        response = requests.delete(url, headers=requisite_headers, auth=auth)

    return response.status_code, response.text
1354130
def process(self, response):
        

        try:
            code = response.status_code

            # 204 - No Content
            if code == 204:
                body = None
            # add an error message to 402 errors
            elif code == 402:
                body = {
                    "message": "Payment Required",
                    "status": "error"
                }
            else:
                body = response.json()

            return Response(code, body, response.content, response)
        except ValueError:
            raise ZencoderResponseError(response, response.content)
536593
def json_or_jsonp(func):
    """"""
    @wraps(func)
    def _(*args, **kwargs):
        mimetype = 'application/javascript'
        callback = request.args.get('callback', None)
        if callback is None:
            content = func(*args, **kwargs)

        else:
            content = "%s(%s)" % (callback, func(*args, **kwargs))
        return current_app.response_class(content, mimetype=mimetype)
    return _
698202
def get_response(cmd, conn):
    """"""
    resp = conn.socket().makefile('rb', -1)
    resp_dict = dict(
        code=0,
        message='',
        isspam=False,
        score=0.0,
        basescore=0.0,
        report=[],
        symbols=[],
        headers={},
    )

    if cmd == 'TELL':
        resp_dict['didset'] = False
        resp_dict['didremove'] = False

    data = resp.read()
    lines = data.split('\r\n')
    for index, line in enumerate(lines):
        if index == 0:
            match = RESPONSE_RE.match(line)
            if not match:
                raise SpamCResponseError(
                    'spamd unrecognized response: %s' % data)
            resp_dict.update(match.groupdict())
            resp_dict['code'] = int(resp_dict['code'])
        else:
            if not line.strip():
                continue
            match = SPAM_RE.match(line)
            if match:
                tmp = match.groupdict()
                resp_dict['score'] = float(tmp['score'])
                resp_dict['basescore'] = float(tmp['basescore'])
                resp_dict['isspam'] = tmp['isspam'] in ['True', 'Yes']
            if not match:
                if cmd == 'SYMBOLS':
                    match = PART_RE.findall(line)
                    for part in match:
                        resp_dict['symbols'].append(part)
            if not match and cmd != 'PROCESS':
                match = RULE_RE.findall(line)
                if match:
                    resp_dict['report'] = []
                    for part in match:
                        score = part[0] + part[1]
                        score = score.strip()
                        resp_dict['report'].append(
                            dict(score=score,
                                 name=part[2],
                                 description=SPACE_RE.sub(" ", part[3])))
            if line.startswith('DidSet:'):
                resp_dict['didset'] = True
            if line.startswith('DidRemove:'):
                resp_dict['didremove'] = True
    if cmd == 'PROCESS':
        resp_dict['message'] = ''.join(lines[4:]) + '\r\n'
    if cmd == 'HEADERS':
        parser = Parser()
        headers = parser.parsestr('\r\n'.join(lines[4:]), headersonly=True)
        for key in headers.keys():
            resp_dict['headers'][key] = headers[key]
    return resp_dict
1257649
def throw_if_bad_response(response):
    """"""
    try:
        response.raise_for_status()
    except RequestException:
        try:
            msg = 'Response code: {}; response body:\n{}'.format(response.status_code, json.dumps(response.json(), indent=2))
            raise CerberusClientException(msg)
        except ValueError:
            msg = 'Response code: {}; response body:\n{}'.format(response.status_code, response.text)
            raise CerberusClientException(msg)
14692
def build_response(cls, code=Status.SYSTEM_ERROR, errors=None):
        
        errors = [errors] if not isinstance(errors, list) else errors
        return cls(code, errors)
821541
def _parse_response(response, clazz, is_list=False, resource_name=None):
        """"""
        target = response.json()[
            resource_name] if resource_name else response.json()
        if is_list:
            return [clazz.from_json(resource) for resource in target]
        else:
            return clazz.from_json(target)
1355454
def _decode_response(response):
    
    status_code = response.status_code

    message = "Status code " + str(status_code)
    try:
      message = CraftAIClient._parse_body(response)["message"]
    except (CraftAiInternalError, KeyError, TypeError):
      pass

    if status_code in [200, 201, 204, 207]:
      return CraftAIClient._parse_body(response)
    else:
      raise CraftAIClient._get_error_from_status(status_code, message)
    return None
659308
def _validate_response(url, response):
    """"""
    if response['status'] not in [GooglePlaces.RESPONSE_STATUS_OK,
                                  GooglePlaces.RESPONSE_STATUS_ZERO_RESULTS]:
        error_detail = ('Request to URL %s failed with response code: %s' %
                        (url, response['status']))
        raise GooglePlacesError(error_detail)
954693
function processResponse(err, res, body) {

    if (err) { return cb(err); }

    if (res.statusCode !== 200) {
      return cb(new ScrapeError('Not OK response from server.', res, body));
    }

    parseBody(body, model, options, cb);

  }
347491
def process_response(self, request, response):
        

        if hasattr(request, 'COUNTRY_CODE'):
            response.set_cookie(
                key=constants.COUNTRY_COOKIE_NAME,
                value=request.COUNTRY_CODE,
                max_age=settings.LANGUAGE_COOKIE_AGE,
                path=settings.LANGUAGE_COOKIE_PATH,
                domain=settings.LANGUAGE_COOKIE_DOMAIN
            )
        return response
444429
def make_response(message, status_code, details=None):
    """"""
    response_body = dict(message=message)
    if details:
        response_body['details'] = details
    response = jsonify(response_body)
    response.status_code = status_code
    return response
75494
def decode_response(status: int, headers: MutableMapping, body: bytes) -> dict:
    
    data = decode_body(headers, body)
    raise_for_status(status, headers, data)
    raise_for_api_error(headers, data)

    return data
320899
def make_response(obj):
    """"""
    if obj is None:
        raise TypeError("Handler return value cannot be None.")
    if isinstance(obj, Response):
        return obj
    return Response(200, body=obj)