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