Кеширование в urllib2?

в моей реализации выглядит так. возможно, это поможет вам:

//[...]

try {
    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);

    zos.putNextEntry(new ZipEntry(file.getName()));

    try {
        final byte[] buf = new byte[BUFFER_SIZE];
        while (true) {
            final int len = bis.read(buf);
            if (len == -1) {
                break;
            }
            zos.write(buf, 0, len);
        }
        zos.flush();
        zos.closeEntry();
    } finally {
        try {
            bis.close();
        } catch (IOException e) {
            LOG.debug("Buffered Stream closing failed");
        } finally {
            fis.close();
        }
    }
} catch (IOException e) {
    throw new Exception(e);
}

//[...]
zos.close
13
задан Yuvi 29 September 2008 в 14:17
поделиться

5 ответов

Вы могли использовать функцию декоратора, такую как:

class cache(object):
    def __init__(self, fun):
        self.fun = fun
        self.cache = {}

    def __call__(self, *args, **kwargs):
        key  = str(args) + str(kwargs)
        try:
            return self.cache[key]
        except KeyError:
            self.cache[key] = rval = self.fun(*args, **kwargs)
            return rval
        except TypeError: # incase key isn't a valid key - don't cache
            return self.fun(*args, **kwargs)

и определяют функцию вроде:

@cache
def get_url_src(url):
    return urllib.urlopen(url).read()

Это предполагает, что Вы не уделение внимания Средствам управления Кэшем HTTP, но просто хотите кэшировать страницу на время приложения

7
ответ дан Will Boyce 29 September 2008 в 14:17
поделиться
  • 1
    Еще раз спасибо, @Josh O' Brien. Я знал debug(), но никогда не использовал browser() непосредственно. That' s большая подсказка! – Christoph_J 5 December 2011 в 09:15

Если Вы не возражаете работать на немного более низком уровне, httplib2 ( https://github.com/httplib2/httplib2) превосходная библиотека HTTP, которая включает кэширующуюся функциональность.

8
ответ дан gsnedders 29 September 2008 в 14:17
поделиться

Этот рецепт ActiveState Python мог бы быть полезным: http://code.activestate.com/recipes/491261/

7
ответ дан danivovich 29 September 2008 в 14:17
поделиться
  • 1
    Кроме того, конечно, don' t запускается Ваши расследования в DT[ ] вызов, который имеет it' s владеют хорошо подобранным но все еще дополнительным слоем обзора правил/поведения! (Для получения информации об этом посмотрите, например, объекты 1.6 и 2.8 vignette("datatable-faq")). – Josh O'Brien 5 December 2011 в 16:44

Я искал что-то подобное, и столкнулся "Рецепт 491261: Кэширование и регулировка для urllib2" , какой danivo отправляется. Проблема, мне действительно не нравится кэширующийся код (много дублирования, большое ручное присоединение путей к файлам вместо того, чтобы использовать os.path.join, staticmethods использования, не очень PEP8'sih и другие вещи, которых я стараюсь избегать)

код является немного более хорошим (по-моему, так или иначе) и является функционально почти таким же, с несколькими дополнениями - главным образом метод "перекэша" (использование в качестве примера может быть, кажутся здесь , или в эти if __name__ == "__main__": раздел в конце кода).

последняя версия может быть найдена в http://github.com/dbr/tvdb_api/blob/master/cache.py , и я вставлю ее здесь для потомства (с моими специализированными удаленными заголовками):

#!/usr/bin/env python
"""
urllib2 caching handler
Modified from http://code.activestate.com/recipes/491261/ by dbr
"""

import os
import time
import httplib
import urllib2
import StringIO
from hashlib import md5

def calculate_cache_path(cache_location, url):
    """Checks if [cache_location]/[hash_of_url].headers and .body exist
    """
    thumb = md5(url).hexdigest()
    header = os.path.join(cache_location, thumb + ".headers")
    body = os.path.join(cache_location, thumb + ".body")
    return header, body

def check_cache_time(path, max_age):
    """Checks if a file has been created/modified in the [last max_age] seconds.
    False means the file is too old (or doesn't exist), True means it is
    up-to-date and valid"""
    if not os.path.isfile(path):
        return False
    cache_modified_time = os.stat(path).st_mtime
    time_now = time.time()
    if cache_modified_time < time_now - max_age:
        # Cache is old
        return False
    else:
        return True

def exists_in_cache(cache_location, url, max_age):
    """Returns if header AND body cache file exist (and are up-to-date)"""
    hpath, bpath = calculate_cache_path(cache_location, url)
    if os.path.exists(hpath) and os.path.exists(bpath):
        return(
            check_cache_time(hpath, max_age)
            and check_cache_time(bpath, max_age)
        )
    else:
        # File does not exist
        return False

def store_in_cache(cache_location, url, response):
    """Tries to store response in cache."""
    hpath, bpath = calculate_cache_path(cache_location, url)
    try:
        outf = open(hpath, "w")
        headers = str(response.info())
        outf.write(headers)
        outf.close()

        outf = open(bpath, "w")
        outf.write(response.read())
        outf.close()
    except IOError:
        return True
    else:
        return False

class CacheHandler(urllib2.BaseHandler):
    """Stores responses in a persistant on-disk cache.

    If a subsequent GET request is made for the same URL, the stored
    response is returned, saving time, resources and bandwidth
    """
    def __init__(self, cache_location, max_age = 21600):
        """The location of the cache directory"""
        self.max_age = max_age
        self.cache_location = cache_location
        if not os.path.exists(self.cache_location):
            os.mkdir(self.cache_location)

    def default_open(self, request):
        """Handles GET requests, if the response is cached it returns it
        """
        if request.get_method() is not "GET":
            return None # let the next handler try to handle the request

        if exists_in_cache(
            self.cache_location, request.get_full_url(), self.max_age
        ):
            return CachedResponse(
                self.cache_location,
                request.get_full_url(),
                set_cache_header = True
            )
        else:
            return None

    def http_response(self, request, response):
        """Gets a HTTP response, if it was a GET request and the status code
        starts with 2 (200 OK etc) it caches it and returns a CachedResponse
        """
        if (request.get_method() == "GET"
            and str(response.code).startswith("2")
        ):
            if 'x-local-cache' not in response.info():
                # Response is not cached
                set_cache_header = store_in_cache(
                    self.cache_location,
                    request.get_full_url(),
                    response
                )
            else:
                set_cache_header = True
            #end if x-cache in response

            return CachedResponse(
                self.cache_location,
                request.get_full_url(),
                set_cache_header = set_cache_header
            )
        else:
            return response

class CachedResponse(StringIO.StringIO):
    """An urllib2.response-like object for cached responses.

    To determine if a response is cached or coming directly from
    the network, check the x-local-cache header rather than the object type.
    """
    def __init__(self, cache_location, url, set_cache_header=True):
        self.cache_location = cache_location
        hpath, bpath = calculate_cache_path(cache_location, url)

        StringIO.StringIO.__init__(self, file(bpath).read())

        self.url     = url
        self.code    = 200
        self.msg     = "OK"
        headerbuf = file(hpath).read()
        if set_cache_header:
            headerbuf += "x-local-cache: %s\r\n" % (bpath)
        self.headers = httplib.HTTPMessage(StringIO.StringIO(headerbuf))

    def info(self):
        """Returns headers
        """
        return self.headers

    def geturl(self):
        """Returns original URL
        """
        return self.url

    def recache(self):
        new_request = urllib2.urlopen(self.url)
        set_cache_header = store_in_cache(
            self.cache_location,
            new_request.url,
            new_request
        )
        CachedResponse.__init__(self, self.cache_location, self.url, True)


if __name__ == "__main__":
    def main():
        """Quick test/example of CacheHandler"""
        opener = urllib2.build_opener(CacheHandler("/tmp/"))
        response = opener.open("http://google.com")
        print response.headers
        print "Response:", response.read()

        response.recache()
        print response.headers
        print "After recache:", response.read()
    main()
3
ответ дан dbr 30 September 2008 в 01:17
поделиться

Эта статья в Yahoo Developer Network - http://developer.yahoo.com/python/python-caching.html - описывает как кэшировать http-вызовы, сделанные через urllib, в память или на диск.

3
ответ дан 1 December 2019 в 19:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: