Overrides ``requests.Session.request`` to renew the IAM cookie
        and then retry the original request (if required).
774351
def request(self, method, url, **kwargs):
        
        # The CookieJar API prevents callers from getting an individual Cookie
        # object by name.
        # We are forced to use the only exposed method of discarding expired
        # cookies from the CookieJar. Internally this involves iterating over
        # the entire CookieJar and calling `.is_expired()` on each Cookie
        # object.
        self.cookies.clear_expired_cookies()

        if self._auto_renew and 'IAMSession' not in self.cookies.keys():
            self.login()

        resp = super(IAMSession, self).request(method, url, **kwargs)

        if not self._auto_renew:
            return resp

        if resp.status_code == 401:
            self.login()
            resp = super(IAMSession, self).request(method, url, **kwargs)

        return resp
968131
def make_duplicate_request(request):
    
    class FakeRequest(object):
        method = 'GET'
        path = request.path
        headers = request.headers
        GET = request.GET
        POST = request.POST
        user = getattr(request, 'user', None)
        cookies = request.cookies
        is_xhr = request.is_xhr
    return FakeRequest()
394553
def prepare_request(self, kwargs):
        
        if self.session_id is not None:
            actual = dt.datetime.now()

            if (self.last_activity + self.inactivity_limit) < actual:
                # session expired
                if self.persist:
                    # request new session
                    self.create_session()
                    actual = dt.datetime.now()
                else:
                    # raise error and recommend to manualy refresh session
                    raise RuntimeError('A non Persistent Session is expired. '
                                       'For consistency reasons this exception is raised. '
                                       'Please try again with manual refresh of the session ')
            self.last_activity = actual

            headers = kwargs.get('headers')
            if headers is None:
                kwargs['headers'] = headers = {}
            headers['workbook-session-id'] = self.session_id
1064732
async def forget_ticket(self, request):
        
        session = await get_session(request)
        session.pop(self.cookie_name, '')
202831
def process_request(self, request):
        
        use_jwt_cookie_requested = request.META.get(USE_JWT_COOKIE_HEADER)
        header_payload_cookie = request.COOKIES.get(jwt_cookie_header_payload_name())
        signature_cookie = request.COOKIES.get(jwt_cookie_signature_name())

        if not use_jwt_cookie_requested:
            metric_value = 'not-requested'
        elif header_payload_cookie and signature_cookie:
            # Reconstitute JWT auth cookie if split cookies are available and jwt cookie
            # authentication was requested by the client.
            request.COOKIES[jwt_cookie_name()] = '{}{}{}'.format(
                header_payload_cookie,
                JWT_DELIMITER,
                signature_cookie,
            )
            metric_value = 'success'
        elif header_payload_cookie or signature_cookie:
            # Log unexpected case of only finding one cookie.
            if not header_payload_cookie:
                log_message, metric_value = self._get_missing_cookie_message_and_metric(
                    jwt_cookie_header_payload_name()
                )
            if not signature_cookie:
                log_message, metric_value = self._get_missing_cookie_message_and_metric(
                    jwt_cookie_signature_name()
                )
            log.warning(log_message)
        else:
            metric_value = 'missing-both'

        monitoring.set_custom_metric('request_jwt_cookie', metric_value)
699940
def _perform_request(self, request, parser=None, parser_args=None, operation_context=None):
        '''
        
        '''
        operation_context = operation_context or _OperationContext()
        retry_context = RetryContext()
        retry_context.is_emulated = self.is_emulated

        # 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)
                    self.authentication.sign_request(request)

                    # Set the request context
                    retry_context.request = request

                    # Log the request before it goes out
                    logger.info("%s Outgoing request: Method=%s, Path=%s, Query=%s, Headers=%s.",
                                client_request_id_prefix,
                                request.method,
                                request.path,
                                request.query,
                                str(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(request.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
                    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:
                # only parse the strings used for logging if logging is at least enabled for CRITICAL
                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)

                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]}
1214415
def request(method, url, headers=None, data=None, session=None):
    
    base_headers = {
        'User-Agent': random_agent()
    }
    if headers is None:
        headers = {}

    base_headers.update(headers)

    if 'Content-Length' in headers:
        del base_headers['Content-Length']

    headers = base_headers
    if session is not None:
        req = session.request
    else:
        req = requests.request

    r = req(method, url, headers=headers, data=data)
    return r
781766
synchronized void renewSession(String prevSessionToken)
  throws SFException, SnowflakeSQLException
  {
    if (sessionToken != null &&
        !sessionToken.equals(prevSessionToken))
    {
      logger.debug("not renew session because session token has not been updated.");
      return;
    }

    SessionUtil.LoginInput loginInput = new SessionUtil.LoginInput();
    loginInput.setServerUrl(
        (String) connectionPropertiesMap.get(SFSessionProperty.SERVER_URL))
        .setSessionToken(sessionToken)
        .setMasterToken(masterToken)
        .setIdToken(idToken)
        .setLoginTimeout(loginTimeout)
        .setDatabaseName(this.getDatabase())
        .setSchemaName(this.getSchema())
        .setRole(this.getRole())
        .setWarehouse(this.getWarehouse());

    SessionUtil.LoginOutput loginOutput = SessionUtil.renewSession(loginInput);

    if (loginOutput.isUpdatedByTokenRequestIssue())
    {
      setCurrentObjects(loginInput, loginOutput);
    }
    sessionToken = loginOutput.getSessionToken();
    masterToken = loginOutput.getMasterToken();
  }
52520
def _check_cookie_and_session
      if session[:__reqref]
        tmp = session[:__reqref]
      else
        if cookies.signed[:__reqref]
          tmp = cookies.signed[:__reqref]
          tmp = _increment_returning_count(tmp)
          _set_cookie(__reqref: tmp)
        else
          tmp = "req=#{request.url}|ref=#{request.referrer}|ret=0"
          _set_cookie(__reqref: tmp)
        end
        session[:__reqref] = tmp
      end
    end
1209094
def process_request(self, request):
        """"""
        
        if COOKIE_KEY in request.COOKIES and \
            request.COOKIES[COOKIE_KEY] == COOKIE_SPAM:
                # Is a known spammer.
                response = HttpResponse("")
                # We do not reveal why it has been forbbiden:
                response.status_code = 404
                if DJANGOSPAM_LOG:
                    logger.log("SPAM REQUEST", request.method,
                       request.path_info,
                       request.META.get("HTTP_USER_AGENT", "undefined"))
                return response
        if DJANGOSPAM_LOG:
            logger.log("PASS REQUEST", request.method, request.path_info,
                       request.META.get("HTTP_USER_AGENT", "undefined"))
        return None
479381
def requests_session(self, *args, **kwargs):
        
        import requests
        auth1 = self.generate_auth()
        return requests.Session(*args, auth=auth1, **kwargs)
548749
def send(self, request, **kwargs):
        
        session = request.context.session

        old_max_redirects = None
        if 'max_redirects' in kwargs:
            warnings.warn("max_redirects in operation kwargs is deprecated, use config.redirect_policy instead",
                          DeprecationWarning)
            old_max_redirects = session.max_redirects
            session.max_redirects = int(kwargs['max_redirects'])

        old_trust_env = None
        if 'use_env_proxies' in kwargs:
            warnings.warn("use_env_proxies in operation kwargs is deprecated, use config.proxies instead",
                          DeprecationWarning)
            old_trust_env = session.trust_env
            session.trust_env = bool(kwargs['use_env_proxies'])

        old_retries = {}
        if 'retries' in kwargs:
            warnings.warn("retries in operation kwargs is deprecated, use config.retry_policy instead",
                          DeprecationWarning)
            max_retries = kwargs['retries']
            for protocol in self._protocols:
                old_retries[protocol] = session.adapters[protocol].max_retries
                session.adapters[protocol].max_retries = max_retries

        try:
            return self.next.send(request, **kwargs)
        finally:
            if old_max_redirects:
                session.max_redirects = old_max_redirects

            if old_trust_env:
                session.trust_env = old_trust_env

            if old_retries:
                for protocol in self._protocols:
                    session.adapters[protocol].max_retries = old_retries[protocol]
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]}
575124
function (req) {
	var cookie = SR.REST.getCookie(req.headers.cookie);
	var session = SR.EventManager.getSession(cookie);
	return session;
}
61209
def _update_token(self, request):
        

        # Refresh our source credentials.
        self._source_credentials.refresh(request)

        body = {
            "delegates": self._delegates,
            "scope": self._target_scopes,
            "lifetime": str(self._lifetime) + "s"
        }

        headers = {
            'Content-Type': 'application/json',
        }

        # Apply the source credentials authentication info.
        self._source_credentials.apply(headers)

        self.token, self.expiry = _make_iam_token_request(
            request=request,
            principal=self._target_principal,
            headers=headers,
            body=body)
610531
async def request(
            self,
            method: str,
            endpoint: str,
            *,
            headers: dict = None,
            params: dict = None,
            data: dict = None) -> dict:
        """"""
        if (self._session_expiry
                and self._session_expiry <= current_epoch_time()):
            raise SessionExpiredError('Session has expired; make a new one!')

        url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint)

        if not headers:
            headers = {}
        headers.update({
            'Tile_app_id': DEFAULT_APP_ID,
            'Tile_app_version': DEFAULT_APP_VERSION,
            'Tile_client_uuid': self.client_uuid,
        })

        async with self._websession.request(method, url, headers=headers,
                                            params=params, data=data) as resp:
            try:
                resp.raise_for_status()
                return await resp.json(content_type=None)
            except client_exceptions.ClientError as err:
                raise RequestError(
                    'Error requesting data from {0}: {1}'.format(
                        endpoint, err)) from None
859699
def Refresh(self):
    
    with requests.Session() as session:
      session.proxies = self.proxy_config.proxies
      session.verify = not self.proxy_config.disable_certificate_validation
      session.cert = self.proxy_config.cafile

      self.creds.refresh(
          google.auth.transport.requests.Request(session=session))