""" Mapping from Orchard to Proper format and formid. Mapping is obtained using the ows-product-configuration microservice. """ import functools import json import time from owsrequest import request import feed_sender.flows.proper_new_releases_tracks.conf.settings as settings from feed_sender.util import correlation_id def call_product_configuration_microservice(): """Return response from ows-product-configuration microservice. Hit up microservice to obtain distribution formats for Proper supply chain. Returns: response_content (list): List of dictionaries containing distribution formats and Proper IDs. """ service_name = settings.PRODUCT_CONFIGURATION_SERVICE_NAME resource = settings.PRODUCT_CONFIGURATION_SERVICE_RESOURCE_PATH application_name = settings.FEED_NAME application_env = settings.ENV corr_id = correlation_id.get_correlation_id() retry = settings.REQUEST_RETRY wait_time = settings.INITIAL_REQUEST_WAIT_TIME retry_wait_exponent = settings.RETRY_WAIT_EXPONENT supply_chain_id = settings.PRODUCT_CONFIGURATION_PROPER_SUPPLY_CHAIN_ID # Call microservice response_content = [] successful_request = False get_request = functools.partial( request.process, application_name, application_env ) while not successful_request and retry > 0: if retry < settings.REQUEST_RETRY: time.sleep(wait_time) wait_time *= retry_wait_exponent response = get_request( 'GET', service_name, resource.format(supply_chain_id=supply_chain_id), corr_id) response_content = json.loads(response.content.decode('utf-8')) successful_request = response.status_code == 200 retry -= 1 # Raise exception if microservice cannot be reached if not successful_request: raise Exception( 'Request to ows-product-configuration microservice failed: ' '{message}'.format(message=response_content.get('message'))) return response_content @functools.lru_cache(maxsize=settings.MAPPING_CACHE_SIZE) def get_distribution_format_mapping(): """Return distribution format mapping dictionary. Parse response from ows-product-configuration into dictionary of distribution format mapping. Returns: mapping (dict): Dictionary of mappings between distribution format ID and Proper format and formid. """ response_content = call_product_configuration_microservice() # Reformat response into dictionary mapping = {} for product in response_content: distribution_format_id = product.get('distribution_format_id', '') if distribution_format_id.isdigit(): proper_format = product.get('proper_format', '') proper_formid = product.get('proper_formid', '') if proper_format and proper_formid: distribution_format_id = int(distribution_format_id) mapping[distribution_format_id] = { 'format': proper_format, 'formid': proper_formid } return mapping