Ask the server for a media and return it to the client browser. Forward cache headers
173624
def media(request, path, hproPk=None):
    """"""

    if not settings.PIAPI_STANDALONE:
        (plugIt, baseURI, _) = getPlugItObject(hproPk)
    else:
        global plugIt, baseURI

    try:
        (media, contentType, cache_control) = plugIt.getMedia(path)
    except Exception as e:
        report_backend_error(request, e, 'meta', hproPk)
        return gen500(request, baseURI)

    if not media:  # No media returned
        raise Http404

    response = HttpResponse(media)
    response['Content-Type'] = contentType
    response['Content-Length'] = len(media)

    if cache_control:
        response['Cache-Control'] = cache_control

    return response
969587
function clientReq(req) {
    if (!req) {
        return (req);
    }

    var host;

    try {
        host = req.host.split(':')[0];
    } catch (e) {
        host = false;
    }

    return ({
        method: req ? req.method : false,
        url: req ? req.path : false,
        address: host,
        port: req ? req.port : false,
        headers: req ? req.headers : false
    });
}
350090
public function postMediaCacheConfigAdv($serverName, $body)
    {
        list($response) = $this->postMediaCacheConfigAdvWithHttpInfo($serverName, $body);
        return $response;
    }
1123042
function makeRequest () {
    request = self.request.apply(null, args);
    requestMiddleware.use(request);
    request.on("response", function (response) {
      var contentEncoding, gzipper;

      //Only cache successful responses
      if (response.statusCode >= 200 && response.statusCode < 300) {
        response.on('error', function (error) {
          self.handleError(error);
        });
        fs.writeFile(self.cacheDirectory + key + ".json", JSON.stringify(response.headers), function (error) {
          if (error) self.handleError(error);
        });

        responseWriter = fs.createWriteStream(self.cacheDirectory + key);

        responseWriter.on('error', function (error) {
          self.handleError(error);
        });

        contentEncoding = response.headers['content-encoding'] || '';
        contentEncoding = contentEncoding.trim().toLowerCase();

        if (contentEncoding === 'gzip') {
          response.on('error', function (error) {
            responseWriter.end();
          });
          response.pipe(responseWriter);
        } else {
          gzipper = zlib.createGzip();
          response.on('error', function (error) {
            gzipper.end();
          });
          gzipper.on('error', function (error) {
            self.handleError(error);
            responseWriter.end();
          });
          responseWriter.on('error', function (error) {
            response.unpipe(gzipper);
            gzipper.end();
          });
          response.pipe(gzipper).pipe(responseWriter);
        }
      }
    });
    self.emit("request", args[0]);
  }
816151
def register_frontend_media(request, media):
    
    if not hasattr(request, '_fluent_contents_frontend_media'):
        request._fluent_contents_frontend_media = Media()

    add_media(request._fluent_contents_frontend_media, media)
1189299
async function fetchAndCache(cache, request) {
  const response = await fetch(request);
  cache.put(request, response.clone());
  return response;
}
6667
function processWebRequest(routeInfo, callbacks) {
    var appName = routeInfo.appName;
    var serverOnly = !!routeInfo.query.server;
    var page = injector.loadModule('app/' + appName + '/pages/' + routeInfo.name + '.page');

    // get the callbacks
    var serverPreprocessing = callbacks.serverPreprocessing || function () { return false; };
    var appAddToModel = callbacks.addToModel || function () {};
    var pageCacheService = callbacks.pageCacheService || defaultPageCache;
    var initialModel, cacheKey;

    return getInitialModel(routeInfo, page)
        .then(function (model) {
            initialModel = model || {};

            // if the server pre-processing returns true, then return without doing anything
            // this is because the pre-processor sent a reply to the user already
            if (serverPreprocessing(routeInfo, page, model)) {
                return true;
            }

            //TODO: may be weird edge cases with this. need to test more to ensure performance and uniqueness
            // but note that we have an hour default timeout for the redis cache just in case
            // and we have the redis LRU config set up so the least recently used will get pushed out
            cacheKey = utensils.checksum(routeInfo.lang + '||' + routeInfo.appName + '||' +
                routeInfo.url + '||' + JSON.stringify(model));

            return pageCacheService.get({ key: cacheKey });
        })
        .then(function (cachedPage) {
            if (cachedPage === true) { return null; }
            if (cachedPage && !serverOnly) { return cachedPage; }

            // allow the app level to modify the model before rendering
            appAddToModel(initialModel, routeInfo);

            // finally use the client side plugin to do the rendering
            return clientPlugin.renderPage(routeInfo, page, initialModel, inlineCssCache[appName + '||' + routeInfo.name]);
        })
        .then(function (renderedPage) {
            if (!serverOnly && renderedPage) {
                pageCacheService.set({ key: cacheKey, value: renderedPage });
            }

            return renderedPage;
        });
}
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()
575460
def getMedia(self):
        
        server = self.server().connect()
        key = '/sync/items/%s' % self.id
        return server.fetchItems(key)
560317
def process_response(self, request, response):
        """"""

        # never cache headers + ETag
        add_never_cache_headers(response)

        if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache:
            # We don't need to update the cache, just return.
            return response
        if request.method != 'GET':
            # This is a stronger requirement than above. It is needed
            # because of interactions between this middleware and the
            # HTTPMiddleware, which throws the body of a HEAD-request
            # away before this middleware gets a chance to cache it.
            return response
        if not response.status_code == 200:
            return response

        # use the precomputed cache_key
        if request._cache_middleware_key:
            cache_key = request._cache_middleware_key
        else:
            cache_key = learn_cache_key(request, response, self.cache_timeout, self.key_prefix)

        # include the orig_time information within the cache
        cache.set(cache_key, (time.time(), response), self.cache_timeout)
        return response
1332341
protected function sendWithCach()
    {
        $cache = $this->pathHtmlCache.$this->name.'_cache.html';
        if (!file_exists($cache)) {
            file_put_contents($cache, $this->content);
        }
        include $cache;
        exit();
    }
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()
990365
def _cached_request(self, base_url, client_id, client_secret,
                        parameters, **kwargs):
        """"""
        key = (base_url, client_id, tuple(parameters.items()))
        cached = self._cache.get(key, {})

        if not cached.get('access_token') or self._expired(cached):
            cached = yield self._request(base_url, client_id, client_secret,
                                         parameters, **kwargs)
            self._cache[key] = cached
            # Purge cache when adding a new item so it doesn't grow too large
            # It's assumed the cache size is small enough that it's OK to loop
            # over the whole cache regularly. If not, could change this to
            # just pop off the oldest one
            self.purge_cache()

        logging.debug('Using a cached token: %s', cached.get('access_token'))
        raise Return(cached)
266770
function get(src) {
      var defer = $q.defer();

      _checkImgCacheReady()
        .then(function() {
          ImgCache.isCached(src, function(path, success) {
            if (success) {
              defer.resolve(path);
            } else {
              defer.reject();
            }
          }, defer.reject);
        })
        .catch(defer.reject);

      return defer.promise;
    }
1242753
def media_image_url(self):
        """"""
        if self.is_nowplaying:
            base = self.server.construct_url(API_URL)
            try:
                image_id = self.session['NowPlayingItem']['ImageTags']['Thumb']
                image_type = 'Thumb'
            except KeyError:
                try:
                    image_id = self.session[
                        'NowPlayingItem']['ImageTags']['Primary']
                    image_type = 'Primary'
                except KeyError:
                    return None
            url = '{0}/Items/{1}/Images/{2}?width=500&tag={3}&api_key={4}'.format(
                base, self.media_id, image_type, image_id, self.server.api_key)
            return url
        else:
            return None
813173
def _get_content(cls, url, headers=HTTP_HEADERS):
        
        session = requests.Session()
        return session.get(url, headers=headers)
940918
private function setHeader ()
    {
        ob_get_clean ();
        header ("Content-Type: video/mp4");
        header ("Cache-Control: max-age=2592000, public");
        header ("Expires: " . gmdate ('D, d M Y H:i:s', time () + 2592000) . ' GMT');
        header ("Last-Modified: " . gmdate ('D, d M Y H:i:s', @filemtime ($this->path)) . ' GMT');
        $this->start = 0;
        $this->size  = filesize ($this->path);
        $this->end   = $this->size - 1;
        header ("Accept-Ranges: 0-" . $this->end);

        if (isset($_SERVER['HTTP_RANGE'])) {

            $c_start = $this->start;
            $c_end   = $this->end;

            list(, $range) = explode ('=', $_SERVER['HTTP_RANGE'], 2);

            if (strpos ($range, ',') !== false) {
                header ('HTTP/1.1 416 Requested Range Not Satisfiable');
                header ("Content-Range: bytes $this->start-$this->end/$this->size");
                exit;
            }

            if ($range == '-') {
                $c_start = $this->size - substr ($range, 1);
            } else {
                $range   = explode ('-', $range);
                $c_start = $range[0];

                $c_end = (isset($range[1]) && is_numeric ($range[1])) ? $range[1] : $c_end;
            }

            $c_end = ($c_end > $this->end) ? $this->end : $c_end;

            if ($c_start > $c_end || $c_start > $this->size - 1 || $c_end >= $this->size) {
                header ('HTTP/1.1 416 Requested Range Not Satisfiable');
                header ("Content-Range: bytes $this->start-$this->end/$this->size");
                exit;
            }

            $this->start = $c_start;
            $this->end   = $c_end;
            $length      = $this->end - $this->start + 1;

            fseek ($this->stream, $this->start);
            header ('HTTP/1.1 206 Partial Content');
            header ("Content-Length: " . $length);
            header ("Content-Range: bytes $this->start-$this->end/" . $this->size);
        } else
            header ("Content-Length: " . $this->size);
    }