:param aiohttp.client._RequestContextManager req_ctx
        :return:
763149
async def _handle_response(self, req_ctx) -> Any:
        
        async with req_ctx as response:
            try:
                response.raise_for_status()
            except aiohttp.client.ClientResponseError as cre:
                text = await response.text(errors='replace')
                self.logger.debug('{cre}; '
                                  'Request info: {cre.request_info}; '
                                  'Response headers: {cre.headers}; '
                                  'Response status: {cre.status}; '
                                  'Content: {text}'.format(cre=cre, text=text))
                raise KeycloakClientError(original_exc=cre)

            try:
                result = await response.json(content_type=None)
            except ValueError:
                result = await response.read()

        return result
682511
@Override
    public RequestCtx handleRequest(HttpServletRequest request,
                                    HttpServletResponse response)
            throws IOException, ServletException {
        LogUtil.statLog(request.getRemoteUser(),
                        Constants.ACTION.RI_FIND_OBJECTS.uri,
                        "FedoraRepository:ResourceIndex",
                        null);

        return null;
    }
289676
@Override
    @SuppressWarnings("deprecation")
    public RequestCtx handleRequest(HttpServletRequest request,
                                    HttpServletResponse response)
            throws IOException, ServletException {
        if (request.getPathInfo() != null) {
            logger.error("Bad request: " + request.getRequestURI());
            throw new ServletException("Bad request: "
                    + request.getRequestURI());
        }

        RequestCtx req = null;

        String pid = request.getParameter("PID");
        String dissID = "sDefPID";
        String methodName = request.getParameter("methodName");
        String dateTime = request.getParameter("asOfDateTime");

        if (logger.isDebugEnabled()) {
            logger.debug("PID: {} sDefPID {} methodName {}", pid, dissID, methodName);
        }

        Map<URI, AttributeValue> actions = new HashMap<URI, AttributeValue>();
        Map<URI, AttributeValue> resAttr;

        String logAction = null;

        // Starting assumption is that we are doing a GetObjectProfile
        actions.put(Constants.ACTION.ID.getURI(),
                    Constants.ACTION.GET_DISSEMINATION
                            .getStringAttribute());
        logAction =
                Constants.ACTION.GET_DISSEMINATION.uri;

        try {
            resAttr = ResourceAttributes.getResources(pid);
            
            if (dissID != null && !dissID.isEmpty()) {
                resAttr.put(Constants.DISSEMINATOR.ID.getURI(),
                            new StringAttribute(dissID));
            }
            if (methodName != null && !methodName.isEmpty()) {
                resAttr.put(Constants.DISSEMINATOR.METHOD.getURI(),
                            new StringAttribute(methodName));
            }
            if (dateTime != null && !dateTime.isEmpty()) {
                resAttr.put(Constants.DATASTREAM.AS_OF_DATETIME.getURI(),
                            DateTimeAttribute.getInstance(dateTime));
            }

            actions.put(Constants.ACTION.API.getURI(),
                        Constants.ACTION.APIA.getStringAttribute());

            req =
                    getContextHandler().buildRequest(getSubjects(request),
                                                     actions,
                                                     resAttr,
                                                     getEnvironment(request));

            LogUtil.statLog(request.getRemoteUser(), logAction, pid, dissID);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServletException(e);
        }

        return req;
    }
654593
def _perform_request(self, request, parser=None, parser_args=None, operation_context=None):
        '''
        
        '''
        operation_context = operation_context or _OperationContext()
        retry_context = RetryContext()

        # Apply the appropriate host based on the location mode
        self._apply_host(request, operation_context, retry_context)

        # Apply common settings to the request
        _update_request(request)

        while(True):
            try:
                try:
                    # Execute the request callback 
                    if self.request_callback:
                        self.request_callback(request)

                    # Add date and auth after the callback so date doesn't get too old and 
                    # authentication is still correct if signed headers are added in the request 
                    # callback. This also ensures retry policies with long back offs 
                    # will work as it resets the time sensitive headers.
                    _add_date_header(request)
                    self.authentication.sign_request(request)

                    # Set the request context
                    retry_context.request = request

                    # Perform the request
                    response = self._httpclient.perform_request(request)

                    # Execute the response callback
                    if self.response_callback:
                        self.response_callback(response)

                    # Set the response context
                    retry_context.response = response

                    # Parse and wrap HTTP errors in AzureHttpError which inherits from AzureException
                    if response.status >= 300:
                        # This exception will be caught by the general error handler
                        # and raised as an azure http exception
                        _http_error_handler(HTTPError(response.status, response.message, response.headers, response.body))

                    # Parse the response
                    if parser:
                        if parser_args:
                            args = [response]
                            args.extend(parser_args)
                            return parser(*args)
                        else:
                            return parser(response)
                    else:
                        return
                except AzureException as ex:
                    raise ex
                except Exception as ex:
                    if sys.version_info >= (3,):
                        # Automatic chaining in Python 3 means we keep the trace
                        raise AzureException(ex.args[0])
                    else:
                        # There isn't a good solution in 2 for keeping the stack trace 
                        # in general, or that will not result in an error in 3
                        # However, we can keep the previous error type and message
                        # TODO: In the future we will log the trace
                        msg = ""
                        if len(ex.args) > 0:
                            msg = ex.args[0]
                        raise AzureException('{}: {}'.format(ex.__class__.__name__, msg))


            except AzureException as ex:
                # Decryption failures (invalid objects, invalid algorithms, data unencrypted in strict mode, etc)
                # will not be resolved with retries.
                if str(ex) == _ERROR_DECRYPTION_FAILURE:
                    raise ex
                # Determine whether a retry should be performed and if so, how 
                # long to wait before performing retry.
                retry_interval = self.retry(retry_context)
                if retry_interval is not None:
                    # Execute the callback
                    if self.retry_callback:
                        self.retry_callback(retry_context)

                    # Sleep for the desired retry interval
                    sleep(retry_interval)
                else:
                    raise ex
            finally:
                # If this is a location locked operation and the location is not set, 
                # this is the first request of that operation. Set the location to 
                # be used for subsequent requests in the operation.
                if operation_context.location_lock and not operation_context.host_location:
                    operation_context.host_location = {retry_context.location_mode: request.host}
1294582
function retrieveContextAtReceiver(req, res) {
  if(redirect(req.params.id, '', '', res)) {
    return;
  }

  switch(req.accepts(['json', 'html'])) {
    case 'html':
      res.sendFile(path.resolve(__dirname + '/../../web/response.html'));
      break;
    default:
      var options = {
        query: 'receivedStrongestBy',
        id: req.params.id,
        omit: [ 'timestamp' ] }; 
      var rootUrl = req.protocol + '://' + req.get('host');
      var queryPath = req.originalUrl;
      req.chickadee.getDevicesContext(req, options, rootUrl, queryPath,
                                      function(response, status) {
        res.status(status).json(response);
      });
      break;
  }
}
977278
function setContext(req, res, next) {
    currentContext = {req: req, res: res};
    next();
}
62939
private static BinaryMemcacheRequest handleTouchRequest(final ChannelHandlerContext ctx, final TouchRequest msg) {
        ByteBuf extras = ctx.alloc().buffer();
        extras.writeInt(msg.expiry());

        byte[] key = msg.keyBytes();
        short keyLength = (short) key.length;
        byte extrasLength = (byte) extras.readableBytes();
        BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key);
        request.setExtras(extras);
        request.setOpcode(OP_TOUCH);
        request.setKeyLength(keyLength);
        request.setTotalBodyLength(keyLength + extrasLength);
        request.setExtrasLength(extrasLength);
        return request;
    }
522228
def _update_request_context_with_user(self, user=None):
        ''''''

        ctx = _request_ctx_stack.top
        ctx.user = self.anonymous_user() if user is None else user
645311
def make_request_with_headers(context):
    
    headers = row_table(context)
    requests.get(context.mock_url, headers=headers)
853907
def _perform_request(self, request, parser=None, parser_args=None, operation_context=None, expected_errors=None):
        '''
        
        '''
        operation_context = operation_context or _OperationContext()
        retry_context = RetryContext()
        retry_context.is_emulated = self.is_emulated

        # if request body is a stream, we need to remember its current position in case retries happen
        if hasattr(request.body, 'read'):
            try:
                retry_context.body_position = request.body.tell()
            except (AttributeError, UnsupportedOperation):
                # if body position cannot be obtained, then retries will not work
                pass

        # Apply the appropriate host based on the location mode
        self._apply_host(request, operation_context, retry_context)

        # Apply common settings to the request
        _update_request(request, self._X_MS_VERSION, self._USER_AGENT_STRING)
        client_request_id_prefix = str.format("Client-Request-ID={0}", request.headers['x-ms-client-request-id'])

        while True:
            try:
                try:
                    # Execute the request callback 
                    if self.request_callback:
                        self.request_callback(request)

                    # Add date and auth after the callback so date doesn't get too old and 
                    # authentication is still correct if signed headers are added in the request 
                    # callback. This also ensures retry policies with long back offs 
                    # will work as it resets the time sensitive headers.
                    _add_date_header(request)

                    try:
                        # request can be signed individually
                        self.authentication.sign_request(request)
                    except AttributeError:
                        # session can also be signed
                        self.request_session = self.authentication.signed_session(self.request_session)

                    # Set the request context
                    retry_context.request = request

                    # Log the request before it goes out
                    # Avoid unnecessary scrubbing if the logger is not on
                    if logger.isEnabledFor(logging.INFO):
                        logger.info("%s Outgoing request: Method=%s, Path=%s, Query=%s, Headers=%s.",
                                    client_request_id_prefix,
                                    request.method,
                                    request.path,
                                    self._scrub_query_parameters(request.query),
                                    str(self._scrub_headers(request.headers)).replace('\n', ''))

                    # Perform the request
                    response = self._httpclient.perform_request(request)

                    # Execute the response callback
                    if self.response_callback:
                        self.response_callback(response)

                    # Set the response context
                    retry_context.response = response

                    # Log the response when it comes back
                    logger.info("%s Receiving Response: "
                                "%s, HTTP Status Code=%s, Message=%s, Headers=%s.",
                                client_request_id_prefix,
                                self.extract_date_and_request_id(retry_context),
                                response.status,
                                response.message,
                                str(response.headers).replace('\n', ''))

                    # Parse and wrap HTTP errors in AzureHttpError which inherits from AzureException
                    if response.status >= 300:
                        # This exception will be caught by the general error handler
                        # and raised as an azure http exception
                        _http_error_handler(
                            HTTPError(response.status, response.message, response.headers, response.body))

                    # Parse the response
                    if parser:
                        if parser_args:
                            args = [response]
                            args.extend(parser_args)
                            return parser(*args)
                        else:
                            return parser(response)
                    else:
                        return
                except AzureException as ex:
                    retry_context.exception = ex
                    raise ex
                except Exception as ex:
                    retry_context.exception = ex
                    raise _wrap_exception(ex, AzureException)

            except AzureException as ex:
                # only parse the strings used for logging if logging is at least enabled for CRITICAL
                exception_str_in_one_line = ''
                status_code = ''
                timestamp_and_request_id = ''
                if logger.isEnabledFor(logging.CRITICAL):
                    exception_str_in_one_line = str(ex).replace('\n', '')
                    status_code = retry_context.response.status if retry_context.response is not None else 'Unknown'
                    timestamp_and_request_id = self.extract_date_and_request_id(retry_context)

                # if the http error was expected, we should short-circuit
                if isinstance(ex, AzureHttpError) and expected_errors is not None and ex.error_code in expected_errors:
                    logger.info("%s Received expected http error: "
                                "%s, HTTP status code=%s, Exception=%s.",
                                client_request_id_prefix,
                                timestamp_and_request_id,
                                status_code,
                                exception_str_in_one_line)
                    raise ex
                elif isinstance(ex, AzureSigningError):
                    logger.info("%s Unable to sign the request: Exception=%s.",
                                client_request_id_prefix,
                                exception_str_in_one_line)
                    raise ex

                logger.info("%s Operation failed: checking if the operation should be retried. "
                            "Current retry count=%s, %s, HTTP status code=%s, Exception=%s.",
                            client_request_id_prefix,
                            retry_context.count if hasattr(retry_context, 'count') else 0,
                            timestamp_and_request_id,
                            status_code,
                            exception_str_in_one_line)

                # Decryption failures (invalid objects, invalid algorithms, data unencrypted in strict mode, etc)
                # will not be resolved with retries.
                if str(ex) == _ERROR_DECRYPTION_FAILURE:
                    logger.error("%s Encountered decryption failure: this cannot be retried. "
                                 "%s, HTTP status code=%s, Exception=%s.",
                                 client_request_id_prefix,
                                 timestamp_and_request_id,
                                 status_code,
                                 exception_str_in_one_line)
                    raise ex

                # Determine whether a retry should be performed and if so, how 
                # long to wait before performing retry.
                retry_interval = self.retry(retry_context)
                if retry_interval is not None:
                    # Execute the callback
                    if self.retry_callback:
                        self.retry_callback(retry_context)

                    logger.info(
                        "%s Retry policy is allowing a retry: Retry count=%s, Interval=%s.",
                        client_request_id_prefix,
                        retry_context.count,
                        retry_interval)

                    # Sleep for the desired retry interval
                    sleep(retry_interval)
                else:
                    logger.error("%s Retry policy did not allow for a retry: "
                                 "%s, HTTP status code=%s, Exception=%s.",
                                 client_request_id_prefix,
                                 timestamp_and_request_id,
                                 status_code,
                                 exception_str_in_one_line)
                    raise ex
            finally:
                # If this is a location locked operation and the location is not set, 
                # this is the first request of that operation. Set the location to 
                # be used for subsequent requests in the operation.
                if operation_context.location_lock and not operation_context.host_location:
                    # note: to cover the emulator scenario, the host_location is grabbed
                    # from request.host_locations(which includes the dev account name)
                    # instead of request.host(which at this point no longer includes the dev account name)
                    operation_context.host_location = {
                        retry_context.location_mode: request.host_locations[retry_context.location_mode]}
353697
def getContext(self):
        """"""
        ctx = ClientContextFactory.getContext(self)
        ctx.set_options(OP_NO_SSLv3)
        return ctx
943082
private void fillRequestContext(RequestContext context) {
        IdManager.makeSureMsgId(context);
        context.setNodeStatus(getSimpleStatus());
        context.setMessageType(MessageType.request);
        context.setSourceNodeId(nodeId);//this node id
    }
554393
def token_middleware(ctx, get_response):
    
    async def middleware(request):
        params = request.setdefault('params', {})
        if params.get("token") is None:
            params['token'] = ctx.token
        return await get_response(request)
    return middleware
403015
def when_i_send_the_request(context, method):
    
    data = context.apiRequestData
    context.apiRequest = context.apiClient.generic(
        method,
        data['url'],
        data=json.dumps(data['params']),
        content_type=data['content-type'],
        format=data['format'],
    )
361716
function requestMetadata (context, router) {
  router = router || context.router;

  return [
    swaggerMetadata,
    swaggerApiMetadata,
    swaggerPathMetadata,
    swaggerOperationMetadata,
    swaggerParamsMetadata,
    swaggerSecurityMetadata
  ];

  /**
   * Sets `req.swagger.api`
   */
  function swaggerApiMetadata (req, res, next) {
    // Only set req.swagger.api if the request is under the API's basePath
    if (context.api) {
      let basePath = util.normalizePath(context.api.basePath, router);
      let reqPath = util.normalizePath(req.path, router);
      if (_.startsWith(reqPath, basePath)) {
        req.swagger.api = context.api;
      }
    }

    next();
  }

  /**
   * Sets `req.swagger.path`
   */
  function swaggerPathMetadata (req, res, next) {
    if (req.swagger.api) {
      let relPath = getRelativePath(req);
      let relPathNormalized = util.normalizePath(relPath, router);

      // Search for a matching path
      Object.keys(req.swagger.api.paths).some((swaggerPath) => {
        let swaggerPathNormalized = util.normalizePath(swaggerPath, router);

        if (swaggerPathNormalized === relPathNormalized) {
          // We found an exact match (i.e. a path with no parameters)
          req.swagger.path = req.swagger.api.paths[swaggerPath];
          req.swagger.pathName = swaggerPath;
          return true;
        }
        else if (req.swagger.path === null && pathMatches(relPathNormalized, swaggerPathNormalized)) {
          // We found a possible match, but keep searching in case we find an exact match
          req.swagger.path = req.swagger.api.paths[swaggerPath];
          req.swagger.pathName = swaggerPath;
        }
      });

      if (req.swagger.path) {
        util.debug("%s %s matches Swagger path %s", req.method, req.path, req.swagger.pathName);
      }
      else {
        util.warn('WARNING! Unable to find a Swagger path that matches "%s"', req.path);
      }
    }

    next();
  }
}
423607
def _request_api(self, **kwargs):
        
        _url = kwargs.get('url')
        _method = kwargs.get('method', 'GET')
        _status = kwargs.get('status', 200)

        counter = 0
        if _method not in ['GET', 'POST']:
            raise ValueError('Method is not GET or POST')

        while True:
            try:
                res = REQ[_method](_url, cookies=self._cookie)
                if res.status_code == _status:
                    break
                else:
                    raise BadStatusException(res.content)
            except requests.exceptions.BaseHTTPError:
                if counter < self._retries:
                    counter += 1
                    continue
                raise MaxRetryError
        self._last_result = res
        return res
680878
private void initRequestFromRpcContext(CmsContainerPageRpcContext context) {

        if (context.getTemplateContext() != null) {
            getRequest().setAttribute(
                CmsTemplateContextManager.ATTR_RPC_CONTEXT_OVERRIDE,
                context.getTemplateContext());
        }
    }