Skip to content

Instantly share code, notes, and snippets.

@koblas
Created October 23, 2012 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save koblas/3940491 to your computer and use it in GitHub Desktop.
Save koblas/3940491 to your computer and use it in GitHub Desktop.
Not caching Exceptions
import logging
from addons.route import route
from .base import BaseHandler
from amazonproduct.api import API, NoExactMatchesFound, TooManyRequests
from tornado import httpclient
from tornado.web import asynchronous, HTTPError
from tornado import gen
from app.util.cache import LRUCache
from StringIO import StringIO
class ioloopAPI(API):
client = httpclient.AsyncHTTPClient()
@gen.engine
def call(self, callback=None, **qargs):
url = self._build_url(**qargs)
response = yield gen.Task(self.client.fetch, url)
callback(self._parse(StringIO(response.body)))
@route('/_aws/lookup')
class AwsLookupHandler(BaseHandler):
cache = LRUCache(10000)
client = httpclient.AsyncHTTPClient()
A_TAG = 'SOMETAG'
AWS_KEY = 'AWS_KEY'
AWS_SECRET = 'NOT TELLING'
ATTRS = {
'Manufacturer': 'manufacturer',
'Brand': 'brand',
'Model': 'Model',
'Title': 'title',
}
@asynchronous
@gen.engine
def get(self):
term = self.get_argument('q')
if term in self.cache:
self.finish(self.cache[term])
return
api = ioloopAPI(self.AWS_KEY, self.AWS_SECRET, 'us', associate_tag='geart06-20')
result = { 'items': [] }
try:
node = yield gen.Task(api.item_search, 'All', Keywords=term, ResponseGroup='Images,ItemAttributes')
for item in node.Items.Item:
a = item.ItemAttributes
dst = { v: unicode(getattr(a, k)) for k, v in self.ATTRS.items() if hasattr(a, k) }
if hasattr(item, 'MediumImage'):
dst['image'] = unicode(item.MediumImage.URL)
result['items'].append(dst)
self.cache[term] = result
except TooManyRequests:
logging.error("Amazon Too Many Requests: %s" % term)
self.send_error(404)
except NoExactMatchesFound:
logging.error("Amazon No Matches: %s" % term)
self.cache[term] = result
self.finish(result)
except :
logging.error("Got Unknown Exception:", e)
raise HTTPError(404)
else:
self.finish(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment