Return whether a REST couchdb operation was successful or not.

    On error will raise a RESTException
972526
def result(self, couchdb_response_text):
    
    result = json.loads(couchdb_response_text)

    if result.get("ok"):
      return True
    elif result.get("error"):
      raise RESTException(
        "%s: %s" % (result.get("error"), result.get("reason"))
      )
    return result
1115774
def fail(self, err='MockupDB query failure', *args, **kwargs):
        
        kwargs.setdefault('flags', 0)
        kwargs['flags'] |= REPLY_FLAGS['QueryFailure']
        kwargs['$err'] = err
        self.replies(*args, **kwargs)
        return True
660335
def rest_put(url, data, timeout, show_error=False):
    ''''''
    try:
        response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\
                                data=data, timeout=timeout)
        return response
    except Exception as exception:
        if show_error:
            print_error(exception)
        return None
447995
def status(self, status_id, raise_exception_on_failure=False):
        """"""
        query = {"output": "json", "user_credentials": self.api_key}

        resp = requests.get(
            "%sstatus/%s" % (self._url, status_id), params=query, timeout=self._timeout
        )

        if raise_exception_on_failure and resp.status_code != 200:
            raise DocumentStatusFailure(resp.content, resp.status_code)

        if resp.status_code == 200:
            as_json = json.loads(resp.content)
            if as_json["status"] == "completed":
                as_json["download_key"] = _get_download_key(as_json["download_url"])
            return as_json
        return resp
579783
function (since, callback) {
      if (opts.aborted) {
        return;
      }
      params.since = since;
      // "since" can be any kind of json object in Coudant/CouchDB 2.x
      /* istanbul ignore next */
      if (typeof params.since === "object") {
        params.since = JSON.stringify(params.since);
      }

      if (opts.descending) {
        if (limit) {
          params.limit = leftToFetch;
        }
      } else {
        params.limit = (!limit || leftToFetch > batchSize) ?
          batchSize : leftToFetch;
      }

      // Set the options for the ajax call
      var xhrOpts = {
        method: method,
        url: genDBUrl(host, '_changes' + paramsToStr(params)),
        timeout: opts.timeout,
        body: body
      };
      lastFetchedSeq = since;

      /* istanbul ignore if */
      if (opts.aborted) {
        return;
      }

      // Get the changes
      setup().then(function () {
        xhr = ajax(opts, xhrOpts, callback);
      }).catch(callback);
    }
508387
def success_response(self, method_resp, **kw):
        
        resp = {
            'status': True,
            'indexing': config.is_indexing(self.working_dir),
            'lastblock': virtualchain_hooks.get_last_block(self.working_dir),
        }

        resp.update(kw)
        resp.update(method_resp)
        
        if self.is_stale():
            # our state is stale
            resp['stale'] = True
            resp['warning'] = 'Daemon has not reindexed since {}'.format(self.last_indexing_time)

        return resp
57163
def valid(cls, token, **kwargs):
        
        try:
            token = yield cls.get(token)
        except couch.NotFound:
            raise Return(False)

        raise Return(token.ttl >= datetime.utcnow())
490392
def response(self, data, rest):
        '''
        '''
        self.connection.write(data)
        data = data[:-len(self.separator)]
        # If we get a QUIT message, close the connection
        # Used by the test suite.
        if data == b'QUIT':
            self.connection.close()
        return data
1346271
private boolean doNotShutdownOnRecoveryFailure() {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "doNotShutdownOnRecoveryFailure");

        boolean doCheck = true;
        Boolean doNotShutdownOnRecoveryFailure = null;

        try {
            doNotShutdownOnRecoveryFailure = AccessController.doPrivileged(
                                                                           new PrivilegedExceptionAction<Boolean>() {
                                                                               @Override
                                                                               public Boolean run() {
                                                                                   Boolean theResult = Boolean.getBoolean("com.ibm.ws.recoverylog.spi.DoNotShutdownOnRecoveryFailure");
                                                                                   if (tc.isDebugEnabled())
                                                                                       Tr.debug(tc, "Have retrieved jvm property with result, " + theResult.booleanValue());
                                                                                   return theResult;
                                                                               }
                                                                           });
        } catch (PrivilegedActionException e) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception getting DoNotShutdownOnRecoveryFailure property", e);
            doNotShutdownOnRecoveryFailure = null;
        }

        if (doNotShutdownOnRecoveryFailure == null)
            doNotShutdownOnRecoveryFailure = Boolean.TRUE;

        doCheck = doNotShutdownOnRecoveryFailure.booleanValue();
        if (tc.isEntryEnabled())
            Tr.exit(tc, "doNotShutdownOnRecoveryFailure", doCheck);
        return doCheck;
    }
616272
def restful(self, path, params):
        

        url = self._get_norm_base_url() + path
        response = requests.get(url, headers=self._get_rest_headers(), params=params)

        if response.status_code != 200:
            raise Exception(response)
        json_result = response.json(object_pairs_hook=OrderedDict)
        if len(json_result) == 0:
            return None
        else:
            return json_result
656020
def rest_post(url, data, timeout, show_error=False):
    ''''''
    try:
        response = requests.post(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\
                                 data=data, timeout=timeout)
        return response
    except Exception as exception:
        if show_error:
            print_error(exception)
        return None
746927
public static void retry(final CouchbaseRequest request, final EventSink<ResponseEvent> responseBuffer) {
        if(!responseBuffer.tryPublishEvent(ResponseHandler.RESPONSE_TRANSLATOR, request, request.observable())) {
            request.observable().onError(CouchbaseCore.BACKPRESSURE_EXCEPTION);
        }
    }
626107
def __process_gprest_response(self, r=None, restType='GET'):
        
        if r is None:
            logging.info('No response for REST '+restType+' request')
            return None

        httpStatus = r.status_code
        logging.info('HTTP status code: %s', httpStatus)

        if httpStatus == requests.codes.ok or \
            httpStatus == requests.codes.created:
            jsonR = r.json()
            if jsonR:
                statusStr = 'REST response status: %s' % \
                    jsonR.get(self.__RESPONSE_STATUS_KEY)
                msgStr = 'REST response message: %s' % \
                    jsonR.get(self.__RESPONSE_MESSAGE_KEY)
                logging.info(statusStr)
                logging.info(msgStr)
                return jsonR
            else:
                logging.warning('Unable to parse JSON body.')
                logging.warning(r.text)
                return None
        logging.warning('Invalid HTTP status code.')
        logging.warning(r.text)
        return r.json()
121861
def json_is_exception(resp):
    
    if not json_is_error(resp):
        return False

    if 'traceback' not in resp.keys() or 'error' not in resp.keys():
        return False

    return True
1107226
def rescue_connection_failure(max_retries = 40)
      success = false
      retries = 0
      while !success
        begin
          yield
          success = true
        rescue mongo_error_type => e
          raise e if (retries += 1) >= max_retries
          sleep 0.25
        end
      end
    end
218489
function () {
    if (req.readyState !== 4) return;
    if (req.status === 200) successCb(null, JSON.parse(req.responseText));
    else {
      var err = { error: 'Sorry, an error ocurred on the server' };

      if (errorCb && typeof errorCb === 'function') return errorCb(err);
      successCb(err, null);
    }
  }
534392
def execute_no_results(self, sock_info, generator):
        
        # Cannot have both unacknowledged write and bypass document validation.
        if self.bypass_doc_val and sock_info.max_wire_version >= 4:
            raise OperationFailure("Cannot set bypass_document_validation with"
                                   " unacknowledged write concern")
        coll = self.collection
        # If ordered is True we have to send GLE or use write
        # commands so we can abort on the first error.
        write_concern = WriteConcern(w=int(self.ordered))
        op_id = _randint()

        for run in generator:
            try:
                if run.op_type == _INSERT:
                    coll._insert(
                        sock_info,
                        run.ops,
                        self.ordered,
                        write_concern=write_concern,
                        op_id=op_id,
                        bypass_doc_val=self.bypass_doc_val)
                elif run.op_type == _UPDATE:
                    for operation in run.ops:
                        doc = operation['u']
                        check_keys = True
                        if doc and next(iter(doc)).startswith('$'):
                            check_keys = False
                        coll._update(
                            sock_info,
                            operation['q'],
                            doc,
                            operation['upsert'],
                            check_keys,
                            operation['multi'],
                            write_concern=write_concern,
                            op_id=op_id,
                            ordered=self.ordered,
                            bypass_doc_val=self.bypass_doc_val)
                else:
                    for operation in run.ops:
                        coll._delete(sock_info,
                                     operation['q'],
                                     not operation['limit'],
                                     write_concern,
                                     op_id,
                                     self.ordered)
            except OperationFailure:
                if self.ordered:
                    break