MoinSupport

MoinRemoteSupport.py

37:6659510890ac
2013-01-19 Paul Boddie Added support for page-specific item storage.
     1 # -*- coding: iso-8859-1 -*-     2 """     3     MoinMoin - MoinRemoteSupport library     4      5     @copyright: 2011, 2012 by Paul Boddie <paul@boddie.org.uk>     6     @license: GNU GPL (v2 or later), see COPYING.txt for details.     7 """     8      9 from MoinMoin.action import cache    10 from MoinMoin import caching    11 import urllib2, time    12     13 def getCachedResource(request, url, arena, scope, max_cache_age):    14     15     """    16     Using the given 'request', return the resource data for the given 'url',    17     accessing a cache entry with the given 'arena' and 'scope' where the data    18     has already been downloaded. The 'max_cache_age' indicates the length in    19     seconds that a cache entry remains valid.    20     21     If the resource cannot be downloaded and cached, None is returned.    22     Otherwise, the form of the data is as follows:    23     24     url <newline> content-type-header <newline> content-body    25     """    26     27     # See if the URL is cached.    28     29     cache_key = cache.key(request, content=url)    30     cache_entry = caching.CacheEntry(request, arena, cache_key, scope=scope)    31     32     # If no entry exists, or if the entry is older than the specified age,    33     # create one with the response from the URL.    34     35     now = time.time()    36     mtime = cache_entry.mtime()    37     38     # NOTE: The URL could be checked and the 'If-Modified-Since' header    39     # NOTE: (see MoinMoin.action.pollsistersites) could be checked.    40     41     if not cache_entry.exists() or now - mtime >= max_cache_age:    42     43         # Access the remote data source.    44     45         cache_entry.open(mode="w")    46     47         try:    48             f = urllib2.urlopen(url)    49             try:    50                 cache_entry.write(url + "\n")    51                 cache_entry.write((f.headers.get("content-type") or "") + "\n")    52                 cache_entry.write(f.read())    53             finally:    54                 cache_entry.close()    55                 f.close()    56     57         # In case of an exception, return None.    58     59         except IOError:    60             if cache_entry.exists():    61                 cache_entry.remove()    62             return None    63     64     # Open the cache entry and read it.    65     66     cache_entry.open()    67     try:    68         return cache_entry.read()    69     finally:    70         cache_entry.close()    71     72 # vim: tabstop=4 expandtab shiftwidth=4