Requires an extra request. Result is cached.
428542
def sids(self):
        """"""
        if self.cid:
            results = get_json(self.cid, operation='sids')
            return results['InformationList']['Information'][0]['SID'] if results else []
928480
public final void requestProcessed (Object result)
    {
        @SuppressWarnings("unchecked") T casted = (T)result;
        requestCompleted(casted);
    }
504123
def request_uniq(func):
    

    def _wrapped(*args, **kwargs):
        data = _get_request_unique_cache()
        return func(data, *args, **kwargs)

    return _wrapped
748145
def process_request(self, request):
        
        content_type = request.META.get('CONTENT_TYPE', '')
        for non_cacheable_type in self.non_cacheable_types:
            if non_cacheable_type in content_type:
                return
        request.body
785538
def _get(self, action, show, proxy, timeout):
        
        silent = self.flags['silent']

        if action in self.cache:
            if action != 'imageinfo' and action != 'labels':
                utils.stderr("+ %s results in cache" % action, silent)
                return
        else:
            self.cache[action] = {}

        if self.flags.get('skip') and action in self.flags['skip']:
            if not self.flags['silent']:
                utils.stderr("+ skipping %s" % action)
            return

        if 'requests' not in self.data:
            self.data['requests'] = []

        if len(self.data['requests']) >= self.REQUEST_LIMIT:
            raise StopIteration("Hit REQUEST_LIMIT = %d" % self.REQUEST_LIMIT)

        if self.data['requests'] and self.REQUEST_DELAY:
            utils.stderr("REQUEST_DELAY = %d seconds" % self.REQUEST_DELAY)
            sleep(self.REQUEST_DELAY)

        # make the request
        qobj = WPToolsQuery(lang=self.params['lang'],
                            variant=self.params.get('variant'),
                            wiki=self.params.get('wiki'),
                            endpoint=self.params.get('endpoint'))
        qstr = self._query(action, qobj)
        req = self._request(proxy, timeout)
        response = req.get(qstr, qobj.status)

        self.cache[action]['query'] = qstr
        self.cache[action]['response'] = response
        self.cache[action]['info'] = req.info

        self.data['requests'].append(action)

        self._set_data(action)

        if show and not self.flags.get('silent'):
            self.show()
41109
public static void addToCache(HttpServletRequest req, RequestProcessor s, WebApp app) {
        //Begin 253010  
        // check if cache is full
        if (_cacheSize.get() >= invocationCacheSize) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) //306998.15
            {
                logger.logp(Level.FINE, CLASS_NAME, "addToCache", "cache is full");
            }
            return;
        }

        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) //306998.15
        {
            logger.logp(Level.FINE, CLASS_NAME, "addToCache", "WebApp = " + app);
        }

        // PK80333 Start
        if (app.getDestroyed()) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) //306998.15
            {
                logger.logp(Level.FINE, CLASS_NAME, "addToCache", "Not caching as the webapp is destroyed");
            }
            return;
        }
        // PK80333 End

        StringBuilder cacheKey = (StringBuilder) cacheKeyStringBuilder.get();
        if (cacheKey == null) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) //306998.15
            {
                logger.logp(Level.FINE, CLASS_NAME, "addToCache", "cache key is null");
            }
            return;
        }
        String cacheKeyStr = cacheKey.toString();
        // Servlet 4.0 : Use CacheServletWrapperFactory
        CacheServletWrapper wrapper =  cacheServletWrapperFactory.createCacheServletWrapper((IServletWrapper) s, req, cacheKeyStr, app);
        if (_cacheMap.putIfAbsent(cacheKeyStr, wrapper) != null) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) //306998.15
            {
                logger.logp(Level.FINE, CLASS_NAME, "addToCache", "Already cached cacheKey --> " + cacheKey);
            }
        } else {
            ((IServletWrapper)s).addServletReferenceListener(wrapper);
            // keep a rough count of the number of items in the cache
            _cacheSize.incrementAndGet();
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) //306998.15 
            {
                logger.logp(Level.FINE, CLASS_NAME, "addToCache", "Added to cache cacheKey --> " + cacheKey + " uri -->" + req.getRequestURI() + " servletWrapper -->"
                                                                      + ((IServletWrapper) s).getServletName());
            }
        }
        // End 253010
    }
318380
def cacheContent(self, request, response, buffer):
        
        content = buffer.getvalue()
        code = int(response.code)
        cache_it = False
        uri, bust = self.processURI(request.uri, PREFIX)
        # Conditions for adding uri response to cache:
        #     * if it was successful i.e. status of in the 200s
        #     * requested using GET
        #     * not busted
        if request.method == "GET" and code / 100 == 2 and not bust:
            cache_control = response.headers.get('cache-control')
            if cache_control:
                params = dict(urlparse.parse_qsl(cache_control))
                if int(params.get('max-age', '0')) > 0:
                    cache_it = True
            if cache_it:
                content = compressBuffer(content)
                self.addResource(content, uri, response.headers)
        buffer.close()
235991
def cache_if_needed(cacheKey, result, menu, context, meta):
    """"""

    if cacheKey:

        # This will be a method in django 1.7
        flat_context = {}
        for d in context.dicts:
            flat_context.update(d)

        del flat_context['csrf_token']

        data = {'result': result, 'menu': menu, 'context': flat_context}

        cache.set('plugit-cache-' + cacheKey, data, meta['cache_time'])
359705
def cached_get(timeout, *params):
    """"""

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(view_or_request, *args, **kwargs):

            # The type of the request gets muddled when using a function based
            # decorator. We must use a function based decorator so it can be
            # used in urls.py.
            request = getattr(view_or_request, "request", view_or_request)

            if not hasattr(_thread_locals, "ultracache_request"):
                setattr(_thread_locals, "ultracache_request", request)

            # If request not GET or HEAD never cache
            if request.method.lower() not in ("get", "head"):
                return view_func(view_or_request, *args, **kwargs)

            # If request contains messages never cache
            l = 0
            try:
                l = len(request._messages)
            except (AttributeError, TypeError):
                pass
            if l:
                return view_func(view_or_request, *args, **kwargs)

            # Compute a cache key
            li = [str(view_or_request.__class__), view_func.__name__]

            # request.get_full_path is implicitly added it no other request
            # path is provided. get_full_path includes the querystring and is
            # the more conservative approach but makes it trivially easy for a
            # request to bust through the cache.
            if not set(params).intersection(set((
                "request.get_full_path()", "request.path", "request.path_info"
            ))):
                li.append(request.get_full_path())

            if "django.contrib.sites" in settings.INSTALLED_APPS:
                li.append(get_current_site_pk(request))

            # Pre-sort kwargs
            keys = list(kwargs.keys())
            keys.sort()
            for key in keys:
                li.append("%s,%s" % (key, kwargs[key]))

            # Extend cache key with custom variables
            for param in params:
                if not isinstance(param, str):
                    param = str(param)
                li.append(eval(param))

            s = ":".join([str(l) for l in li])
            hashed = hashlib.md5(s.encode("utf-8")).hexdigest()
            cache_key = "ucache-get-%s" % hashed
            cached = cache.get(cache_key, None)
            if cached is None:
                # The get view as outermost caller may bluntly set _ultracache
                request._ultracache = []
                response = view_func(view_or_request, *args, **kwargs)
                content = None
                if isinstance(response, TemplateResponse):
                    content = response.render().rendered_content
                elif isinstance(response, HttpResponse):
                    content = response.content
                if content is not None:
                    headers = getattr(response, "_headers", {})
                    cache.set(
                        cache_key,
                        {"content": content, "headers": headers},
                        timeout
                    )
                    cache_meta(request, cache_key)
            else:
                response = HttpResponse(cached["content"])
                # Headers has a non-obvious format
                for k, v in cached["headers"].items():
                    response[v[0]] = v[1]

            return response

        return _wrapped_view
    return decorator
279626
private function _process() {

        // if caching is enabled but path doesn't exist, or is not writable
        if ($this->cache !== false && (!is_dir($this->cache['path']) || !is_writable($this->cache['path'])))

            // trigger an error and stop execution
            trigger_error('Cache path does not exists or is not writable', E_USER_ERROR);

        // iterate through the requests to process
        foreach ($this->_requests as $index => $request) {

            // if callback function is defined but it doesn't exists
            if ($request['callback'] != '' && !is_callable($request['callback']))

                // trigger an error and stop execution
                // the check is for when callback functions are defined as methods of a class
                trigger_error('Callback function "' . (is_array($request['callback']) ? array_pop($request['callback']) : $request['callback']) . '" does not exist', E_USER_ERROR);

            // if caching is enabled
            if ($this->cache !== false) {

                // get the name to be used for the cache file associated with the request
                $cache_file = $this->_get_cache_file_name($request);

                // if cache file exists and is not expired
                if (file_exists($cache_file) && filemtime($cache_file) + $this->cache['lifetime'] > time()) {

                    // if we have a callback
                    if ($request['callback'] != '') {

                        // prepare the arguments to pass to the callback function
                        $arguments = array_merge(

                            // made of the result from the cache file...
                            array(unserialize($this->cache['compress'] ? gzuncompress(file_get_contents($cache_file)) : file_get_contents($cache_file))),

                            // ...and any additional arguments (minus the first 2)
                            (array)$request['arguments']

                        );

                        // feed them as arguments to the callback function
                        call_user_func_array($request['callback'], $arguments);

                        // remove this request from the list so it doesn't get processed
                        unset($this->_requests[$index]);

                    }

                }

            }

        }

        // if there are any requests to process
        if (!empty($this->_requests)) {

            // initialize the multi handle
            // this will allow us to process multiple handles in parallel
            $this->_multi_handle = curl_multi_init();

            // queue the first batch of requests
            // (as many as defined by the "threads" property, or less if there aren't as many requests)
            $this->_queue_requests();

            // a flag telling the library if there are any requests currently processing
            $running = null;

            // loop
            do {

                // get status update
                while (($status = curl_multi_exec($this->_multi_handle, $running)) == CURLM_CALL_MULTI_PERFORM);

                // if no request has finished yet, keep looping
                if ($status != CURLM_OK) break;

                // if a request was just completed, we'll have to find out which one
                while ($info = curl_multi_info_read($this->_multi_handle)) {

                    // get handle of the completed request
                    $handle = $info['handle'];

                    // get content associated with the handle
                    $content = curl_multi_getcontent($handle);

                    // get the handle's ID
                    $resource_number = preg_replace('/Resource id #/', '', $handle);

                    // get the information associated with the request
                    $request = $this->_running['fh' . $resource_number];

                    // create a new object in which we will store all the data associated with the handle,
                    // as properties of this object
                    $result = new stdClass();

                    // get information about the request
                    $result->info = curl_getinfo($handle);

                    // extend the "info" property with the original URL
                    $result->info = array('original_url' => $request['url']) + $result->info;

                    // if request was a POST
                    if (isset($request['options'][CURLOPT_POSTFIELDS]) && $request['options'][CURLOPT_POSTFIELDS])

                        // put POST parameters in the response
                        $result->post = $request['options'][CURLOPT_POSTFIELDS];

                    // last request headers
                    $result->headers['last_request'] =

                        (

                            // if CURLINFO_HEADER_OUT is set
                            isset($request['options'][CURLINFO_HEADER_OUT]) &&

                            // if CURLINFO_HEADER_OUT is TRUE
                            $request['options'][CURLINFO_HEADER_OUT] == 1 &&

                            // if we actually have this information
                            isset($result->info['request_header'])

                        // extract request headers
                        ) ? $this->_parse_headers($result->info['request_header'], true) : '';

                    // remove request headers information from its previous location
                    unset($result->info['request_header']);

                    // get headers (unless we were explicitly told not to)
                    $result->headers['responses'] = (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1) ?

                        $this->_parse_headers(substr($content, 0, $result->info['header_size'])) :

                        '';

                    // get output (unless we were explicitly told not to)
                    $result->body = !isset($request['options'][CURLOPT_NOBODY]) || $request['options'][CURLOPT_NOBODY] == 0 ?

                        (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1 ?

                        substr($content, $result->info['header_size']) :

                        $content) :

                        '';

                    // if _htmlentities is set to TRUE, we're not doing a binary transfer and we have a body, run htmlentities() on it
                    if ($this->_htmlentities && !isset($request['options'][CURLOPT_BINARYTRANSFER]) && $result->body != '') {

                        // since PHP 5.3.0, htmlentities will return an empty string if the input string contains an
                        // invalid code unit sequence within the given encoding (utf-8 in our case)
                        // so take care of that
                        if (defined(ENT_IGNORE)) $result->body = htmlentities($result->body, ENT_IGNORE, 'utf-8');

                        // for PHP versions lower than 5.3.0
                        else htmlentities($result->body);

                    }

                    // get CURLs response code and associated message
                    $result->response = array($this->_response_messages[$info['result']], $info['result']);

                    // if we have a callback
                    if (isset($request['callback']) && $request['callback'] != '') {

                        // prepare the arguments to pass to the callback function
                        $arguments = array_merge(

                            // made of the "result" object...
                            array($result),

                            // ...and any additional arguments
                            $request['arguments']

                        );

                        // if downloaded a file
                        if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) {

                            // we make a dummy array with the first first 2 elements (which we also remove from the $arguments[0]->info array)
                            $tmp_array = array_splice($arguments[0]->info, 0, 2);

                            // make available the name we saved the file with
                            // (we need to merge the first 2 elements, our new array and the rest of the elements)
                            $arguments[0]->info = array_merge($tmp_array, array('downloaded_filename' => $this->_running['fh' . $resource_number]['file_name']), $arguments[0]->info);

                        }

                        // feed them as arguments to the callback function
                        // and save the callback's response, if any
                        $callback_response = call_user_func_array($request['callback'], $arguments);

                    // if no callback function, we assume the response is TRUE
                    } else $callback_response = true;

                    // if caching is enabled and the callback function did not return FALSE
                    if ($this->cache !== false && $callback_response !== false) {

                        // get the name of the cache file associated with the request
                        $cache_file = $this->_get_cache_file_name($request);

                        // cache the result
                        file_put_contents($cache_file, $this->cache['compress'] ? gzcompress(serialize($result)) : serialize($result));

                        // set rights on the file
                        chmod($cache_file, intval($this->cache['chmod'], 8));

                    }

                    // if there are more URLs to process and we're don't pause between batches of requests, queue the next one(s)
                    if (!empty($this->_requests) && !$this->pause_interval) $this->_queue_requests();

                    // remove the handle that we finished processing
                    // this needs to be done *after* we've already queued a new URL for processing
                    curl_multi_remove_handle($this->_multi_handle, $handle);

                    // make sure the handle gets closed
                    curl_close($handle);

                    // if we downloaded a file
                    if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER])

                        // close the associated file pointer
                        fclose($this->_running['fh' . $resource_number]['file_handler']);

                    // we don't need the information associated with this request anymore
                    unset($this->_running['fh' . $resource_number]);

                }

                // waits until curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM or until the timeout, whatever happens first
                // call usleep() if a select returns -1 - workaround for PHP bug: https://bugs.php.net/bug.php?id=61141
                if ($running && curl_multi_select($this->_multi_handle) === -1) usleep(100);

            // as long as there are threads running or requests waiting in the queue
            } while ($running || !empty($this->_running));

            // close the multi curl handle
            curl_multi_close($this->_multi_handle);

        }

    }
1193914
def cache_add(self, request, response):
        
        logger.debug("adding response to the cache")

        """
        checking for valid code
-       """
        code = response.code
        try:
            utils.check_code(code)
        except utils.InvalidResponseCode:  # pragma no cover
            logger.error("Invalid response code")
            return

        """
        return if max_age is 0
        """
        if response.max_age == 0:
            return

        """
        Initialising new cache element based on the mode and updating the cache
        """

        if self.mode == defines.FORWARD_PROXY:
            new_key = CacheKey(request)
        else:
            new_key = ReverseCacheKey(request)

        logger.debug("MaxAge = {maxage}".format(maxage=response.max_age))
        new_element = CacheElement(new_key, response, request, response.max_age)

        self.cache.update(new_key, new_element)
        logger.debug("Cache Size = {size}".format(size=self.cache.debug_print()))
701486
public void get(URI uri, Header[] additionalRequestHeaders,
			Credentials credentials) {
		ra.getExecutorService().execute(
				new AsyncGetHandler(ra, handle, uri, additionalRequestHeaders,
						credentials));
	}
10773
static void preHandleMultipartRequest(HttpServletRequest request)
        throws ServletException
    {
        MultipartRequestHandler multipartHandler = getCachedMultipartHandler(request);
        
        if (multipartHandler == null)
        {
            multipartHandler = getMultipartHandler(request);
            
            if (multipartHandler != null)
            {
                //
                // Run the request through the handler, and cache the handler in the outer request.
                //
                multipartHandler.handleRequest(request);
                HttpServletRequest outerRequest = ScopedServletUtils.getOuterRequest(request);
                outerRequest.setAttribute(PREHANDLED_MULTIPART_REQUEST_ATTR, multipartHandler);
            }
        }
    }
364741
def search_response(self, request):
        
        logger.debug("Cache Search Response")

        if self.cache.is_empty() is True:
            logger.debug("Empty Cache")
            return None

        """
        create a new cache key from the request
        """

        if self.mode == defines.FORWARD_PROXY:
            search_key = CacheKey(request)
        else:
            search_key = ReverseCacheKey(request)

        response = self.cache.get(search_key)

        return response
604360
function ( appRequest, appResponse ) {
    var cacheHtml = null,
        cacheJson = null,
        cacheName = null,
        slugged = slug( appRequest.params[ 0 ].replace( /\//g, "-" ).replace( /-$/g, "" ) ),
        reqSlug = ( slugged === "" ) ? "-homepage" : slugged,
        url = appRequest.params[ 0 ],
        qrs = {};

    cacheName = ("page" + reqSlug);

    // Querystring?
    for ( var i in appRequest.query ) {
        qrs[ i ] = appRequest.query[ i ];

        // Unique cache file name including queries
        if ( i !== "format" && i !== "password" && i !== "nocache" ) {
            cacheName += ("-" + i + "--" + qrs[ i ]);
        }
    }

    cacheHtml = sqsCache.get( (cacheName + ".html") );
    cacheJson = sqsCache.get( (cacheName + ".json") );

    // 404 JSON?
    if ( cacheJson && !pageNotFoundJson ) {
        setPageNotFoundJson( cacheJson );
    }

    // Nocache?
    if ( appRequest.query.nocache !== undefined ) {
        cacheJson = null;
        cacheHtml = null;

        sqsCache.remove( (cacheName + ".html") );
        sqsCache.remove( (cacheName + ".json") );
        sqsCache.remove( (cacheName + "-main-content.html") );
    }

    // Search?
    if ( slugged === "search" ) {
        if ( cacheHtml ) {
            appResponse.status( 200 ).send( cacheHtml );

        } else {
            sqsWare.getHtml( url, qrs, function ( error, data ) {
                if ( !error ) {
                    appResponse.status( 200 ).send( data.html );

                    sqsCache.set( (cacheName + ".html"), data.html );

                } else {
                    // Handle errors
                    nsl.log( "error", ("Error requesting system search page => " + error) );
                }
            });
        }

        return;
    }

    // Cache?
    if ( cacheJson && cacheHtml && !rJson.test( appRequest.query.format ) ) {
        sqsTemplate.renderTemplate( qrs, cacheJson, cacheHtml, function ( tpl ) {
            appResponse.status( 200 ).send( tpl );
        });

        return;
    }

    // JSON?
    // Supports `json` and `json-pretty`
    if ( rJson.test( appRequest.query.format ) ) {
        if ( cacheJson ) {
            cacheJson.nodeServer = true;

            appResponse.status( 200 ).json( cacheJson );

        } else {
            sqsWare.getJson( url, qrs, function ( error, json ) {
                if ( !error ) {
                    json.json.nodeServer = true;

                    sqsCache.set( (cacheName + ".json"), json.json );

                    appResponse.status( 200 ).json( json.json );

                } else {
                    // Handle errors
                    nsl.log( "error", ("Error requesting page json => " + error) );
                }
            });
        }

    // Main-Content
    } else if ( appRequest.query.format === "main-content" ) {
        cacheHtml = sqsCache.get( (cacheName + "-main-content.html") );

        if ( cacheHtml ) {
            appResponse.status( 200 ).send( cacheHtml );

        } else {
            sqsWare.getHtml( url, qrs, function ( error, data ) {
                if ( !error ) {
                    appResponse.status( 200 ).send( data.html );

                    sqsCache.set( (cacheName + "-main-content.html"), data.html );

                } else {
                    // Handle errors
                    nsl.log( "error", ("Error requesting main-content for page => " + error) );
                }
            });
        }

    // Request page?
    } else {
        sqsWare.getJsonAndHtml( url, qrs, function ( error, data ) {
            if ( !error ) {
                sqsCache.set( (cacheName + ".json"), data.json.json );
                sqsCache.set( (cacheName + ".html"), data.html.html );

                // 404 JSON?
                if ( !pageNotFoundJson ) {
                    setPageNotFoundJson( data.json.json );
                }

                sqsTemplate.renderTemplate( qrs, data.json.json, sqsCache.get( (cacheName + ".html") ), function ( tpl ) {
                    appResponse.status( 200 ).send( tpl );
                });

            } else {
                // Handle errors
                nsl.log( "error", ("Error requesting page => " + error) );

                // Could be a 404 though so serve it
                if ( data.html.status === 404 || data.json.status === 404 ) {
                    //appResponse.status( 200 ).send( data.html.html );
                    sqsTemplate.renderTemplate( qrs, pageNotFoundJson, data.html.html, function ( tpl ) {
                        appResponse.status( 404 ).send( tpl );
                    });

                    nsl.log( "warn", ("Request responded with server code 404 for => `" + url + "`") );

                    return;
                }
            }
        });
    }
}
429354
function() {
    var e = this.get('extra_params') || e;
    e.cache_buster = new Date().getTime();
    this.set('extra_params', e);
    this.trigger('change', this);
  }
131573
def _pre_request(self, url, method = u"get", data = None, headers=None, **kwargs):
        
        return (url, method, data, headers, kwargs)