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 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 """ 23 24 # See if the URL is cached. 25 26 cache_key = cache.key(request, content=url) 27 cache_entry = caching.CacheEntry(request, arena, cache_key, scope=scope) 28 29 # If no entry exists, or if the entry is older than the specified age, 30 # create one with the response from the URL. 31 32 now = time.time() 33 mtime = cache_entry.mtime() 34 35 # NOTE: The URL could be checked and the 'If-Modified-Since' header 36 # NOTE: (see MoinMoin.action.pollsistersites) could be checked. 37 38 if not cache_entry.exists() or now - mtime >= max_cache_age: 39 40 # Access the remote data source. 41 42 cache_entry.open(mode="w") 43 44 try: 45 f = urllib2.urlopen(url) 46 try: 47 cache_entry.write(url + "\n") 48 cache_entry.write((f.headers.get("content-type") or "") + "\n") 49 cache_entry.write(f.read()) 50 finally: 51 cache_entry.close() 52 f.close() 53 54 # In case of an exception, return None. 55 56 except IOError: 57 if cache_entry.exists(): 58 cache_entry.remove() 59 return None 60 61 # Open the cache entry and read it. 62 63 cache_entry.open() 64 try: 65 return cache_entry.read() 66 finally: 67 cache_entry.close() 68 69 # vim: tabstop=4 expandtab shiftwidth=4