Enable client-side caching for the current request
199880
def enable_cache(self):
        """"""
        self.set_header('Cache-Control', 'max-age=%d, public' % CACHE_TIME)

        d = datetime.datetime.now() + datetime.timedelta(seconds=CACHE_TIME)
        self.set_header('Expires', d.strftime('%a, %d %b %Y %H:%M:%S'))

        self.set_header('access-control-max-age', CACHE_TIME)
138311
function _disableCache() {
        var result = new $.Deferred();

        if (brackets.inBrowser) {
            result.resolve();
        } else {
            var port = brackets.app.getRemoteDebuggingPort ? brackets.app.getRemoteDebuggingPort() : 9234;
            Inspector.getDebuggableWindows("127.0.0.1", port)
                .fail(result.reject)
                .done(function (response) {
                    var page = response[0];
                    if (!page || !page.webSocketDebuggerUrl) {
                        result.reject();
                        return;
                    }
                    var _socket = new WebSocket(page.webSocketDebuggerUrl);
                    // Disable the cache
                    _socket.onopen = function _onConnect() {
                        _socket.send(JSON.stringify({ id: 1, method: "Network.setCacheDisabled", params: { "cacheDisabled": true } }));
                    };
                    // The first message will be the confirmation => disconnected to allow remote debugging of Brackets
                    _socket.onmessage = function _onMessage(e) {
                        _socket.close();
                        result.resolve();
                    };
                    // In case of an error
                    _socket.onerror = result.reject;
                });
        }

        return result.promise();
    }
891380
def _build_request_factory(cls, session: AppSession):
        '''
        '''
        def request_factory(*args, **kwargs):
            request = session.factory.class_map['Request'](*args, **kwargs)

            user_agent = session.args.user_agent or session.default_user_agent

            request.fields['User-Agent'] = user_agent

            if session.args.referer:
                request.fields['Referer'] = session.args.referer

            for header_string in session.args.header:
                request.fields.parse(header_string)

            if session.args.http_compression:
                request.fields['Accept-Encoding'] = 'gzip, deflate'

            if session.args.no_cache:
                request.fields['Cache-Control'] = 'no-cache, must-revalidate'
                request.fields['Pragma'] = 'no-cache'

            return request

        return request_factory
511021
function ( uri ) {
		var item = cache.items[uri];

		return item !== undefined && item.expires !== undefined && item.expires < new Date();
	}
658387
def enable_cache():
    """"""
    try:
        import requests_cache
    except ImportError as err:
        sys.stderr.write('Failed to enable cache: {0}\n'.format(str(err)))
        return
    if not os.path.exists(CACHE_DIR):
        os.makedirs(CACHE_DIR)
    requests_cache.install_cache(CACHE_FILE)
661654
protected void saveRequestedUrl(final C context, final List<Client> currentClients, AjaxRequestResolver ajaxRequestResolver) {
        if (ajaxRequestResolver == null || !ajaxRequestResolver.isAjax(context)) {
            savedRequestHandler.save(context);
        }
    }
440968
function _cacheGetHandleByUrl( sUrl )
{
	let oRet;
	let arrResult;

	if ( 'string' !== typeof sUrl || 0 === sUrl.length )
	{
		return null;
	}

	//	...
	oRet		= null;
	sUrl		= sUrl.trim().toLowerCase();
	arrResult	= m_arrCacheOutboundPeers.filter( oSocket => oSocket.peer === sUrl );
	if ( Array.isArray( arrResult ) && 1 === arrResult.length )
	{
		oRet = arrResult[ 0 ];
	}

	return oRet;
}
261810
def dispatch(self, request, *args, **kwargs):
        
        if not graphql_api_settings.CACHE_ACTIVE:
            return self.super_call(request, *args, **kwargs)

        cache = caches["default"]
        operation_ast = self.get_operation_ast(request)
        if operation_ast and operation_ast.operation == "mutation":
            cache.clear()
            return self.super_call(request, *args, **kwargs)

        cache_key = "_graplql_{}".format(self.fetch_cache_key(request))
        response = cache.get(cache_key)

        if not response:
            response = self.super_call(request, *args, **kwargs)

            # cache key and value
            cache.set(cache_key, response, timeout=graphql_api_settings.CACHE_TIMEOUT)

        return response
457230
def fetch_synchronous(self, endpoint_name, query_params=None):
        """"""

        endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name

        if query_params is None:
            query_params = {}

        return self._request_client.get(endpoint_url, query_params)
248368
def request(self, method, url, **kwargs):
        
        # short circuit if cache isn't configured
        if not self.cache_storage:
            resp = super(CachingSession, self).request(method, url, **kwargs)
            resp.fromcache = False
            return resp

        resp = None
        method = method.lower()

        request_key = self.key_for_request(method, url, **kwargs)

        if request_key and not self.cache_write_only:
            resp = self.cache_storage.get(request_key)

        if resp:
            resp.fromcache = True
        else:
            resp = super(CachingSession, self).request(method, url, **kwargs)
            # save to cache if request and response meet criteria
            if request_key and self.should_cache_response(resp):
                self.cache_storage.set(request_key, resp)
            resp.fromcache = False

        return resp
915531
async function fetchCacheableResource(request) {
  const cache = await caches.open(CACHE_NAME);
  const cachedResponse = await cache.match(request);

  if (!navigator.onLine) {
    // We are offline, and we know it.  Just return the cached response, to
    // avoid a bunch of pointless errors in the JS console that will confuse
    // us developers.  If there is no cached response, this will just be a
    // failed request.
    return cachedResponse;
  }

  if (cachedResponse) {
    // We have it in cache.  Try to fetch a live version and update the cache,
    // but limit how long we will wait for the updated version.
    try {
      return timeout(NETWORK_TIMEOUT, fetchAndCache(cache, request));
    } catch (error) {
      // We tried to fetch a live version, but it either failed or took too
      // long.  If it took too long, the fetch and cache operation will continue
      // in the background.  In both cases, we should go ahead with a cached
      // version.
      return cachedResponse;
    }
  } else {
    // We should have this in cache, but we don't.  Fetch and cache a fresh
    // copy and then return it.
    return fetchAndCache(cache, request);
  }
}
38203
function fromCache(request) {
  return caches.open(CACHE).then(function (cache) {
    return cache.match(request).then(function (matching) {
      return matching || Promise.reject('no-match');
    });
  });
}
891985
function refresh() {
        $this->client = new $this->clientClassName($this->accessToken, $this->spaceId, $this->cacher);
        $this->requestDecorator = new RequestDecorator();
        $this->requestDecorator->setResource($this->resourceName);
    }
110283
function makeRequest(title, cacheHitExpected, next) {
  var start = Date.now();

  request({
    url: 'http://localhost:1337/'
  }, function(err, data, body) {
    var time = Date.now() - start;

    console.log(title);
    console.log('  status:', data.statusCode);
    console.log('  body  :', body);
    console.log('  time  :', time);

    common.verify(function() {
      common.shouldUseCache(cacheHitExpected, time);
    });

    console.log();

    next();
  });
}
984626
def cached_request(self, request):
        
        cache_url = self.cache_url(request.url)
        logger.debug('Looking up "%s" in the cache', cache_url)
        cc = self.parse_cache_control(request.headers)

        # Bail out if the request insists on fresh data
        if "no-cache" in cc:
            logger.debug('Request header has "no-cache", cache bypassed')
            return False

        if "max-age" in cc and cc["max-age"] == 0:
            logger.debug('Request header has "max_age" as 0, cache bypassed')
            return False

        # Request allows serving from the cache, let's see if we find something
        cache_data = self.cache.get(cache_url)
        if cache_data is None:
            logger.debug("No cache entry available")
            return False

        # Check whether it can be deserialized
        resp = self.serializer.loads(request, cache_data)
        if not resp:
            logger.warning("Cache entry deserialization failed, entry ignored")
            return False

        # If we have a cached 301, return it immediately. We don't
        # need to test our response for other headers b/c it is
        # intrinsically "cacheable" as it is Permanent.
        # See:
        #   https://tools.ietf.org/html/rfc7231#section-6.4.2
        #
        # Client can try to refresh the value by repeating the request
        # with cache busting headers as usual (ie no-cache).
        if resp.status == 301:
            msg = (
                'Returning cached "301 Moved Permanently" response '
                "(ignoring date and etag information)"
            )
            logger.debug(msg)
            return resp

        headers = CaseInsensitiveDict(resp.headers)
        if not headers or "date" not in headers:
            if "etag" not in headers:
                # Without date or etag, the cached response can never be used
                # and should be deleted.
                logger.debug("Purging cached response: no date or etag")
                self.cache.delete(cache_url)
            logger.debug("Ignoring cached response: no date")
            return False

        now = time.time()
        date = calendar.timegm(parsedate_tz(headers["date"]))
        current_age = max(0, now - date)
        logger.debug("Current age based on date: %i", current_age)

        # TODO: There is an assumption that the result will be a
        #       urllib3 response object. This may not be best since we
        #       could probably avoid instantiating or constructing the
        #       response until we know we need it.
        resp_cc = self.parse_cache_control(headers)

        # determine freshness
        freshness_lifetime = 0

        # Check the max-age pragma in the cache control header
        if "max-age" in resp_cc:
            freshness_lifetime = resp_cc["max-age"]
            logger.debug("Freshness lifetime from max-age: %i", freshness_lifetime)

        # If there isn't a max-age, check for an expires header
        elif "expires" in headers:
            expires = parsedate_tz(headers["expires"])
            if expires is not None:
                expire_time = calendar.timegm(expires) - date
                freshness_lifetime = max(0, expire_time)
                logger.debug("Freshness lifetime from expires: %i", freshness_lifetime)

        # Determine if we are setting freshness limit in the
        # request. Note, this overrides what was in the response.
        if "max-age" in cc:
            freshness_lifetime = cc["max-age"]
            logger.debug(
                "Freshness lifetime from request max-age: %i", freshness_lifetime
            )

        if "min-fresh" in cc:
            min_fresh = cc["min-fresh"]
            # adjust our current age by our min fresh
            current_age += min_fresh
            logger.debug("Adjusted current age from min-fresh: %i", current_age)

        # Return entry if it is fresh enough
        if freshness_lifetime > current_age:
            logger.debug('The response is "fresh", returning cached response')
            logger.debug("%i > %i", freshness_lifetime, current_age)
            return resp

        # we're not fresh. If we don't have an Etag, clear it out
        if "etag" not in headers:
            logger.debug('The cached response is "stale" with no etag, purging')
            self.cache.delete(cache_url)

        # return the original handler
        return False
927086
def connectCached(self, endpoint, protocolFactory,
                      extraWork=lambda x: x,
                      extraHash=None):
        
        key = endpoint, extraHash
        D = Deferred()
        if key in self.cachedConnections:
            D.callback(self.cachedConnections[key])
        elif key in self.inProgress:
            self.inProgress[key].append(D)
        else:
            self.inProgress[key] = [D]
            endpoint.connect(
                _CachingClientFactory(
                    self, key, protocolFactory,
                    extraWork))
        return D
927746
function cacheGet(key, options) {
    if (shouldCache(options)) {
      return;
    }

    if (self.options.cache === 'memory') {
      return self.cache[key];
    }

    return self.options.cache.get(key);
  }