"""Model for ows-track.""" import logging import requests import sentry_sdk import config import const from utils import string logger = logging.getLogger(config.APPLICATION_NAME) def get_track_artist_info(tuid): """Get information about track from ows-track microservice. Args: tuid (int): track unique id Returns: dict: information about track """ result = { 'artist_id': 0, 'artist_name': '' } response = _fetch_from_ows_track(tuid, 'track_id', const.OWS_TRACK_ENDPOINT) if response.status_code == 200: info = response.json() artist = next( (a for a in info['artists'] if a['type'] == 'performer'), None) if artist: result['artist_id'] = artist['track_artist_id'] result['artist_name'] = string.cleanup_unicode(artist['name']) return result def get_all_tracks_by_product_id(pid): """Get information about track from ows-track microservice. Args: pid (int): product id Returns: list: information about tracks """ result = [] response = _fetch_from_ows_track(pid, 'product_id', const.OWS_TRACK_PRODUCT_ENDPOINT) if response.status_code == 200: tracks = response.json()['items'] for track in tracks: artist = next( (a for a in track['artists'] if a['type'] == 'performer'), None) if artist: track['artist_id'] = artist['track_artist_id'] track['artist_name'] = string.cleanup_unicode(artist['name']) else: track['artist_id'] = 0 track['artist_name'] = '' result = tracks return result def _fetch_from_ows_track(tuid, id_type, endpoint): url = const.SERVICE_URL.format( environment=config.ENVIRONMENT, service_name=const.OWS_TRACK_SERVICE_NAME, path=endpoint.format(tuid)) retry = 2 response = requests.get(url) while retry: if response.status_code not in (200, 404): retry -= 1 if retry: logger.info(f'Retrying to get track info for {id_type}: {tuid}') response = requests.get(url) else: retry = 0 if response.status_code not in (200, 404): try: error_msg = response.json() except Exception: error_msg = response.content.decode() error = 'Failed to get info from ows-track. {}: {} ' \ 'error_code: {} error_message: {}'. \ format(id_type, tuid, response.status_code, error_msg) sentry_sdk.capture_message(error) raise Exception(const.OWS_TRACK_ERROR) return response