"""Interface to ows-search microservice.""" from oto import response as oto_response import requests import config def _construct_ows_search_url_params(params): return '&'.join(['{}={}'.format(key, val) for key, val in params.items() if val is not None]) def _construct_ows_search_url( term, labelid, subaccountid, context, token, filter_track_type): """Generate an ows-search url based on a search term. Args: term (str): Search term. labelid (str): Label ID. subaccountid (str | None): Subaccountid ID context (str): Search context. token (str): Search token. filter_track_type (str): Track type filter. Returns: url (str): an ows-search url for the given search term. """ params_str = _construct_ows_search_url_params({ 'context': context, 'token': token, 'term': term, 'filter.label_id': labelid, 'filter.subaccount_id': subaccountid, 'filter.track_type': filter_track_type }) return '{base_url}?{params_str}'.format( base_url=config.OWS_SEARCH_BASE_URL, params_str=params_str) def _get_search_results( term, account_type, account_id, context=config.SEARCH_CONTEXT, token=config.SEARCH_TOKEN, filter_track_type=config.SEARCH_FILTER_TRACK_TYPE): """Query ows-search microservice and retrieve results. Args: term (str): Search term. account_type (str): Vendor or subaccount. account_id (str): Numerical account identifier. context (str): Search context. token (str): Search token. filter_track_type (str): Track type filter. Returns: response.Response: Response with search results. """ headers = { config.GRASS_ACCOUNT_TYPE: account_type, config.GRASS_ACCOUNT_ID: str(account_id) } labelid = account_id subaccountid = None url = _construct_ows_search_url( term, labelid, subaccountid, context, token, filter_track_type) results = requests.get(url, headers=headers) results_json = results.json() if results_json['isError']: return oto_response.create_fatal_response( message=results_json['errorMessage']) else: return oto_response.Response(results_json) def search_tracks(term, account_type, account_id): """Search tracks. Args: term (str): Search term. account_type (str): Vendor or subaccount account_id (str): Numerical account identifier Returns: response.Response: Response with track search results. """ return _get_search_results(term, account_type, account_id)