"""Application Handlers. Requests are redirected to handlers, which are responsible for getting information from the URL and passing it down to the logic layer. The way each layer talks to each other is through Response objects which defines the type status of the data and the data itself. Please note: the Orchard uses the term handlers over views as convention for clarity See: oto.response for more details. """ import traceback import boto3 from flask import g from flask import jsonify from flask import request from owsresponse import response from owsresponse.adaptors.flask import flaskify from personalize import config from personalize.api import app from personalize.logic import spotify PERSONALIZE_RUNTIME = boto3.client( 'personalize-runtime', region_name='us-east-2' ) @app.route('/track_list', methods=['GET']) def generate_playlist(): """Generate a playlist.""" try: item_list = [] algorithm = request.args.get('algorithm') campaign_arn = request.args.get('arn') num_results = 50 if algorithm == 'sims': item_id = request.args.get('item_id') recommendations_response = PERSONALIZE_RUNTIME.get_recommendations( campaignArn=campaign_arn, itemId=item_id, numResults=num_results ) item_list = recommendations_response['itemList'] elif algorithm == 'hrnn': user_id = request.args.get('user_id') recommendations_response = PERSONALIZE_RUNTIME.get_recommendations( campaignArn=campaign_arn, userId=user_id, numResults=num_results ) item_list = recommendations_response['itemList'] artist_removed_track_list = spotify.remove_submitted_artist( item_id, item_list) deduped_artist_track_list = spotify.remove_duplicate_artists( artist_removed_track_list) response = jsonify(deduped_artist_track_list) response.headers.add('Access-Control-Allow-Origin', '*') return response except: # noqa return traceback.format_exc() @app.route(config.HEALTH_CHECK, methods=['GET']) def health(): """Check the health of the application.""" return jsonify({'status': 'ok'}) @app.errorhandler(500) def exception_handler(error): """Handle error when uncaught exception is raised. Default exception handler. Note: Exception will also be sent to Sentry if config.SENTRY is set. Returns: flask.Response: A 500 response with JSON 'code' & 'message' payload. """ message = ( 'The server encountered an internal error ' 'and was unable to complete your request.') g.log.exception(error) return flaskify(response.create_fatal_response(message))