Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Feb 27th, 2012  |  syntax: None  |  size: 1.75 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. from amazonproduct import API
  2. import os
  3. from hashlib import md5
  4.  
  5.  
  6. old_fetch = API._fetch
  7. old_build_url = API._build_url
  8. old_init = API.__init__
  9.  
  10. def new_fetch(self, url):
  11.     """
  12.     Monkey patch for the _fetch method of amazon API.
  13.     Preserve url of the last call  and cache response into the file
  14.     (no cache invalidation yet)
  15.     """
  16.     self._last_url = url
  17.  
  18.     if self.enable_cache:
  19.         path = os.path.join(self.CACHEDIR, self._cachename)
  20.         if os.path.isfile(path):
  21.             f = open(path, 'r')
  22.             return f
  23.    
  24.     resp = old_fetch(self, url)
  25.    
  26.     if self.enable_cache:
  27.         f = open(path, 'w+')
  28.         f.write(resp.read())
  29.         resp.seek(0)
  30.         f.close()
  31.  
  32.     return resp
  33.  
  34. def new_init(self, access_key_id, secret_access_key, locale,
  35.              associate_tag=None, processor=None, enable_cache=True):
  36.     """
  37.     Monkey patch for the __init__ method of amazon API
  38.     Takes one more param, enable_cache and store it and tries to create
  39.     cache dir if needed
  40.     """
  41.     self.enable_cache = enable_cache
  42.  
  43.     if self.enable_cache and not os.path.isdir(self.CACHEDIR):
  44.         os.mkdir(self.CACHEDIR)
  45.  
  46.     return old_init(self, access_key_id, secret_access_key, locale,
  47.                     associate_tag, processor)
  48.                    
  49. def new_build_url(self, **qargs):
  50.     """
  51.     Saving hash of meaningful part of the url to use it as cache key
  52.     """
  53.     url = old_build_url(self, **qargs)
  54.     cachename = "&".join([chunk for chunk in url.split('&') \
  55.         if chunk.find('Timestamp') != 0 and chunk.find('Signature') != 0])
  56.        
  57.     m = md5()
  58.     m.update(cachename)
  59.     self._cachename = m.hexdigest()
  60.        
  61.     return url
  62.  
  63. API.CACHEDIR = 'cache'
  64.    
  65. API._fetch = new_fetch
  66. API.__init__ = new_init
  67. API._build_url = new_build_url