Created
March 14, 2017 12:46
-
-
Save chussenot/976b19ae8063fa61d5eaf1a60f003cd2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import os | |
import urllib2 | |
import time | |
import json | |
from dnbdirect2 import DnBPlus | |
from cache import Cache | |
from parsers import ProfileParser | |
from errors import ( | |
ALL_ERRORS, ViewError, BadRequestError, UnauthorizedError, | |
ForbiddenError, NotFoundError, ConflictError, TooManyRequestsError | |
) | |
class Router(object): | |
ROUTES = { | |
'executives': {'method':'plus_executives'}, | |
'profile': {'method':'profile_with_linkage'}, | |
'check': {'method':'profile_with_linkage'}, | |
'match': {'method':'identity_resolution'} | |
} | |
AWS_DEFAULT_REGION = 'eu-west-1' | |
TABLE_NAME_SUF = "-datafoundation-buffer" | |
def __init__(self): | |
logging.basicConfig() | |
log = logging.getLogger() | |
log.setLevel(logging.DEBUG) | |
log.debug('Start router') | |
self.log = log | |
def route(self, path, event): | |
self.log.debug('routing => ' + path) | |
try: | |
method = self.ROUTES[path]['method'] | |
except KeyError as e: | |
raise BadRequestError('Route not found') | |
payload = event['body'] | |
self.log.debug('method => ' + method) | |
buffy = Cache(self.AWS_DEFAULT_REGION, event['stage'] + self.TABLE_NAME_SUF) | |
doc = buffy.get_doc(method, payload) | |
if doc is None: | |
service = DnBPlus(os.environ['API_KEY'], os.environ['API_SECRET']) | |
retries = 1 | |
success = False | |
# Manage High load phases | |
while not success: | |
try: | |
doc = service.__getattribute__(method)(payload) | |
success = True | |
except urllib2.HTTPError as e: | |
if e.code == 429: # Too many requests | |
wait = retries * 30 | |
time.sleep(wait) | |
retries += 1 | |
elif e.code == 301: | |
data = json.loads(e.read()) | |
profile = ProfileParser(data) | |
duns = profile.getValue('organization.dunsControlStatus.dunsTransfers')[0]['retainedDUNS'] | |
payload['duns'] = duns | |
else: | |
raise BadRequestError(e.code) | |
buffy.set_doc(method, payload, doc) | |
return doc | |
else: | |
return doc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment