Generic REST Operation handler.
778004
def _rest_op(self, operation, suburi, request_headers, request_body):
        """"""

        url = urlparse.urlparse('https://' + self.host + suburi)
        # Used for logging on redirection error.
        start_url = url.geturl()

        LOG.debug(self._("%(operation)s %(url)s"),
                  {'operation': operation, 'url': start_url})

        if request_headers is None or not isinstance(request_headers, dict):
            request_headers = {}

        # Use self.login/self.password and Basic Auth
        if self.login is not None and self.password is not None:
            auth_data = self.login + ":" + self.password
            hr = "BASIC " + base64.b64encode(
                auth_data.encode('ascii')).decode("utf-8")
            request_headers['Authorization'] = hr

        if request_body is not None:
            if (isinstance(request_body, dict)
                    or isinstance(request_body, list)):
                request_headers['Content-Type'] = 'application/json'
            else:
                request_headers['Content-Type'] = ('application/'
                                                   'x-www-form-urlencoded')

        """Helper methods to retry and keep retrying on redirection - START"""

        def retry_if_response_asks_for_redirection(response):
            # NOTE:Do not assume every HTTP operation will return a JSON
            # request_body. For example, ExtendedError structures are only
            # required for HTTP 400 errors and are optional elsewhere as they
            # are mostly redundant for many of the other HTTP status code.
            # In particular, 200 OK responses should not have to return any
            # request_body.

            # NOTE:  this makes sure the headers names are all lower cases
            # because HTTP says they are case insensitive
            # Follow HTTP redirect
            if response.status_code == 301 and 'location' in response.headers:
                retry_if_response_asks_for_redirection.url = (
                    urlparse.urlparse(response.headers['location']))
                LOG.debug(self._("Request redirected to %s."),
                          retry_if_response_asks_for_redirection.url.geturl())
                return True
            return False

        @retrying.retry(
            # Note(deray): Return True if we should retry, False otherwise.
            # In our case, when the url response we receive asks for
            # redirection then we retry.
            retry_on_result=retry_if_response_asks_for_redirection,
            # Note(deray): Return True if we should retry, False otherwise.
            # In our case, when it's an IloConnectionError we don't retry.
            # ``requests`` already takes care of issuing max number of
            # retries if the URL service is unavailable.
            retry_on_exception=(
                lambda e: not isinstance(e, exception.IloConnectionError)),
            stop_max_attempt_number=REDIRECTION_ATTEMPTS)
        def _fetch_response():

            url = retry_if_response_asks_for_redirection.url

            kwargs = {'headers': request_headers,
                      'data': json.dumps(request_body)}
            if self.cacert is not None:
                kwargs['verify'] = self.cacert
            else:
                kwargs['verify'] = False

            LOG.debug(self._('\n\tHTTP REQUEST: %(restreq_method)s'
                             '\n\tPATH: %(restreq_path)s'
                             '\n\tBODY: %(restreq_body)s'
                             '\n'),
                      {'restreq_method': operation,
                       'restreq_path': url.geturl(),
                       'restreq_body': request_body})

            request_method = getattr(requests, operation.lower())
            try:
                response = request_method(url.geturl(), **kwargs)
            except Exception as e:
                LOG.debug(self._("Unable to connect to iLO. %s"), e)
                raise exception.IloConnectionError(e)

            return response

        """Helper methods to retry and keep retrying on redirection - END"""

        try:
            # Note(deray): This is a trick to use the function attributes
            # to overwrite variable/s (in our case ``url``) and use the
            # modified one in nested functions, i.e. :func:`_fetch_response`
            # and :func:`retry_if_response_asks_for_redirection`
            retry_if_response_asks_for_redirection.url = url

            response = _fetch_response()
        except retrying.RetryError as e:
            # Redirected for REDIRECTION_ATTEMPTS - th time. Throw error
            msg = (self._("URL Redirected %(times)s times continuously. "
                          "URL used: %(start_url)s More info: %(error)s") %
                   {'start_url': start_url, 'times': REDIRECTION_ATTEMPTS,
                    'error': str(e)})
            LOG.debug(msg)
            raise exception.IloConnectionError(msg)

        response_body = {}
        if response.text:
            try:
                response_body = json.loads(response.text)
            except (TypeError, ValueError):
                # Note(deray): If it doesn't decode as json, then
                # resources may return gzipped content.
                # ``json.loads`` on python3 raises TypeError when
                # ``response.text`` is gzipped one.
                response_body = (
                    self._get_response_body_from_gzipped_content(url,
                                                                 response))

        LOG.debug(self._('\n\tHTTP RESPONSE for %(restreq_path)s:'
                         '\n\tCode: %(status_code)s'
                         '\n\tResponse Body: %(response_body)s'
                         '\n'),
                  {'restreq_path': url.geturl(),
                   'status_code': response.status_code,
                   'response_body': response_body})
        return response.status_code, response.headers, response_body
1120448
def rest_put(url, data, timeout):
    ''''''
    try:
        response = requests.put(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\
                                data=data, timeout=timeout)
        return response
    except Exception as e:
        print('Get exception {0} when sending http put to url {1}'.format(str(e), url))
        return None
680497
def reqresp_middleware(api=None):
    """"""
    def decorator(middleware_generator):
        apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_generator)

        class MiddlewareRouter(object):
            __slots__ = ('gen', )

            def process_request(self, request, response):
                self.gen = middleware_generator(request)
                return self.gen.__next__()

            def process_response(self, request, response, resource, req_succeeded):
                return self.gen.send((response, resource))

        apply_to_api.http.add_middleware(MiddlewareRouter())
        return middleware_generator
    return decorator
356690
function rest(func) {
      if (!isFun(func)) throwErr('fun');
      var start = func.length - 1;
      return function () {
        var len = Math.max(arguments.length - start, 0);
        var rst = Array(len), i = -1;
        while (++i < len) rst[i] = arguments[start + i];
        var args = Array(start + 1);
        for (i = 0; i < start; i ++) args[i] = arguments[i];
        args[start] = rst;
        switch (args.length) {
          case 0: return func.call(this);
          case 1: return func.call(this, args[0]);
          case 2: return func.call(this, args[0], args[1]);
          case 3: return func.call(this, args[0], args[1], args[2]);
        }
        return func.apply(this, args);
      };
    }
185475
def request(self, method, path, **options):
        """"""
        options = self._merge_options(options)
        url = options['base_url'] + path
        retry_count = 0
        request_options = self._parse_request_options(options)
        self._add_version_header(request_options)
        while True:
            try:
                response = getattr(self.session, method)(
                    url, auth=self.auth, **request_options)
                if response.status_code in STATUS_MAP:
                    raise STATUS_MAP[response.status_code](response)
                elif 500 <= response.status_code < 600:
                    # Any unhandled 500 is a server error.
                    raise error.ServerError(response)
                else:
                    if options['full_payload']:
                        return response.json()
                    else:
                        return response.json()['data']
            except error.RetryableAsanaError as e:
                if retry_count < options['max_retries']:
                    self._handle_retryable_error(e, retry_count)
                    retry_count += 1
                else:
                    raise e
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)
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()
573859
def handle_json_wrapper_GET(self, handler, parsed_params):
    """"""
    schedule = self.server.schedule
    result = handler(parsed_params)
    content = ResultEncoder().encode(result)
    self.send_response(200)
    self.send_header('Content-Type', 'text/plain')
    self.send_header('Content-Length', str(len(content)))
    self.end_headers()
    self.wfile.write(content)
673349
def rest_post(url, data, timeout, rethrow_exception=False):
    ''''''
    try:
        response = requests.post(url, headers={'Accept': 'application/json', 'Content-Type': 'application/json'},\
                                 data=data, timeout=timeout)
        return response
    except Exception as e:
        if rethrow_exception is True:
            raise
        print('Get exception {0} when sending http post to url {1}'.format(str(e), url))
        return None
1308665
def post(url, data=None, json=None, **kwargs):
    """"""
    _set_content_type(kwargs)
    if _content_type_is_json(kwargs) and data is not None:
        data = dumps(data)
    _log_request('POST', url, kwargs, data)
    response = requests.post(url, data, json, **kwargs)
    _log_response(response)
    return response
363358
def call(self, operation, data):
        """"""
        print('API call [{0}:{1}], method - {2}, data - {3}'.format(
            self.host, self.api_key, operation, repr(data)))
610611
def _rest_patch(self, suburi, request_headers, request_body):
        
        return self._rest_op('PATCH', suburi, request_headers, request_body)
1188243
function toRestifyHandler(handler) {
        if ((typeof handler === 'function') && (handler.length !== 3)) {
            //Wrap `virgilio-http` type handlers.
            handler = restifyHandler.bind(this, handler);
        }
        return handler;
    }
55111
function RestOperation(serviceClient, operation) {
  this.status = OperationState.Inited;
  this.operationId = -1;
  this._callbackArguments = null;

  // setup callback and args
  this._userCallback = arguments[arguments.length - 1];
  var sliceEnd = arguments.length;
  if(azureutil.objectIsFunction(this._userCallback)) {
    sliceEnd--;
  } else {
    this._userCallback = null;
  }
  var operationArguments = Array.prototype.slice.call(arguments).slice(2, sliceEnd);

  this.run = function(cb) {
    var func = serviceClient[operation];
    if(!func) {
      throw new ArgumentError('operation', util.format('Unknown operation %s in serviceclient', operation));
    } else {
      if(!cb) cb = this._userCallback;
      operationArguments.push(cb);
      this.status = OperationState.RUNNING;
      func.apply(serviceClient, operationArguments);
      operationArguments = operation = null;
    }
  };

  this._fireUserCallback = function () {
    if(this._userCallback) {
      this._userCallback.apply(null, this._callbackArguments);
    }
  };
}
1199036
def help(rest):
	""""""
	rs = rest.strip()
	if rs:
		# give help for matching commands
		for handler in Handler._registry:
			if handler.name == rs.lower():
				yield '!%s: %s' % (handler.name, handler.doc)
				break
		else:
			yield "command not found"
		return

	# give help for all commands
	def mk_entries():
		handlers = (
			handler
			for handler in Handler._registry
			if type(handler) is pmxbot.core.CommandHandler
		)
		handlers = sorted(handlers, key=operator.attrgetter('name'))
		for handler in handlers:
			res = "!" + handler.name
			if handler.aliases:
				alias_names = (alias.name for alias in handler.aliases)
				res += " (%s)" % ', '.join(alias_names)
			yield res
	o = io.StringIO(" ".join(mk_entries()))
	more = o.read(160)
	while more:
		yield more
		time.sleep(0.3)
		more = o.read(160)
368724
function handleOperation(handlers, mode, checkArity, req, res, done) {
  // parse path:
  // - first part is the operation name
  // - the following components of the path are used as arguments
  const parsedParts = parsePath(req);
  if (parsedParts[0].length === 0) {
    done(new ModofunError(403, 'NoOperation', 'Operation must be specified!'));
    return;
  }
  const [operation, ...args] = parsedParts;

  if (operation && handlers.hasOwnProperty(operation)) {
    // the stack of operation specific middleware
    let operationMiddleware = [];
    // operation handler
    let operationHandler = handlers[operation];

    if (Array.isArray(operationHandler)) {
      // if an array is passed, add operation specific middleware
      // last item in the array should be the operation handler
      operationMiddleware = operationHandler.slice(0, -1);
      operationHandler = operationHandler[operationHandler.length-1];

    } else if (typeof operationHandler !== 'function') {
      // otherwise return internal error
      done(new ModofunError(500, 'InvalidConfig', 'Handler must be a function or array'));
      return;
    }

    // call middleware stack with same req/res context
    runMiddlewareStack(operationMiddleware, req, res, (err) => {
      if (err) {
        done(err);
        return;
      }
      try {
        // call handler function
        if (mode === FUNCTION_MODE) {
          invokeFunctionHandler(operationHandler, args, checkArity, req, res, done);
        } else {
          invokeHTTPHandler(operationHandler, args, req, res, done);
        }
      } catch(err) {
        done(err);
      }
    });

  } else {
    // fail if requested operation cannot be resolved
    done(new ModofunError(404, 'NotFound', `No handler for: ${operation}`));
    return;
  }
}
138068
function processTerm (handler, obj = {}, isDefault) {
  let req = {
    term: this._request.term.then(value => {
      assignRequest(req, this._request, obj)
      if (this._request.error && !isDefault) return null
      if (isDefault) req.error = null
      return handler(value, req)
    })
  }
  return new v(this._client, req)
}