def get(self): """ Main function to search songs by given level value and returns the average difficulty for all songs :method: GET :return: data_dict: dictionary with following keys: 'total': total number of found songs 'avg_value': the average difficulty value for all songs 'result': list of found songs """ args = request.args level = args.get("level", None) if level is None: abort(404, error_message='Missing level parameter') is_match = re.match('\d', level) if not is_match: abort(404, error_message='Except numeric value for level parameter') output = Song().search_by_level(level_value=level) avg_value = Song().get_average_difficulty() total_item = 0 if output is not None: total_item = len(output) return jsonify({'total': total_item, 'avg_value': avg_value, 'result': output})
def post(self): """ Handler function for adding song data. :return: """ data = request.get_json() app.logger.debug('Post JSON data from request: %s', data) created_id = Song().create(**data) return {"created_id": created_id}
def get(self): """ Main function to fetch list of song by 'limit' and 'page' parameter. If no parameter given then list all songs :return: data_dict: dictionary with following keys: 'result': rows data 'total': total number of found items """ args = request.args # retrieve args from query string app.logger.debug('Arguments from request: %s', args) page_size = args.get("limit", None) page_number = args.get("page", None) show_all = 1 if page_size is not None: if page_size == '': raise ValueError('Value in limit parameter cannot be empty string') show_all = 0 page_size = int(page_size) if page_number is None or page_number == '': page_number = 1 else: page_number = int(page_number) if page_number <= 0: page_number = 1 if show_all: output = Song().list_all() else: output = Song().list(page_size=page_size, page_number=page_number) return jsonify({'result': output, 'total': len(output)})
def test_delete(self): """ Test deleting data row from song collection :return: """ params = { "artist": "Mr Fastfinger", "title": "Awaki-Waki", "difficulty": 15, "level": 13, "released": "2012-05-11" } created_id = None status = False with self.app.app_context(): created_id = Song(is_test_mode=1).create(**params) if created_id is not None: print('== created_id: %s', created_id) status = Song().delete(song_id=created_id) self.assertTrue(status)
def test_create(self): """ Test creating data row to song collection :return: """ params = { "artist": "Mr Fastfinger", "title": "Awaki-Waki", "difficulty": 15, "level": 13, "released": "2012-05-11" } created_id = None with self.app.app_context(): created_id = Song().create(**params) print("Created row id ", created_id) self.assertIsNotNone(created_id)
def get(self): """ Main function to search songs by keywords. :return: data_dict: dictionary with following keys: 'total': total number of found songs 'result': list of dictionary of song data """ args = request.args message = args.get("message", None) if message is None or message == '': abort(404, error_message='Missing message parameter') output = Song().search_by(key_search=message) total_item = 0 if output is not None: total_item = len(output) return jsonify({'total': total_item, 'result': output})
def create_app(config_name=None): """ Create and configure the app :param config_name: string of configuration. Possible values are 'testing', 'development' and 'production' :return: app: app object """ app = Flask(__name__, instance_relative_config=True) is_test_mode = 0 if config_name is None: config_name = 'development' if config_name == 'testing': is_test_mode = 1 app.config.from_object(app_config[config_name]) app.config.from_pyfile('config.py', silent=True) if is_test_mode == 1: app.config["MONGO_DBNAME"] = "test_songs_db" app.config["MONGO_URI"] = "mongodb://localhost:27017/test_songs_db" else: app.config["MONGO_DBNAME"] = "songs_db" app.config["MONGO_URI"] = "mongodb://localhost:27017/songs_db" app.config['mongodb'] = PyMongo(app) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass with app.app_context(): dbnames_list = Song().get_dbnames() # Import data from a file if songs collection does not exist in the database if len(dbnames_list) == 0: SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) json_url = os.path.join(SITE_ROOT, "data/songs.json") create_from_file(file_path=json_url) # Define end points api = Api(app) api.add_resource(ListSong, "/songs", endpoint="songs", resource_class_kwargs={'config_name': config_name}) api.add_resource(AddSong, "/songs/add", endpoint="songs_add", resource_class_kwargs={'config_name': config_name}) api.add_resource(ListSongByLevel, "/songs/avg/difficulty", endpoint="songs_by_level", resource_class_kwargs={'config_name': config_name}) api.add_resource(SearchSong, "/songs/search", endpoint="search_songs", resource_class_kwargs={'config_name': config_name}) api.add_resource(RateSong, "/songs/rating", endpoint="rate_songs", resource_class_kwargs={'config_name': config_name}) api.add_resource(ListRating, "/rating", endpoint="ratings", resource_class_kwargs={'config_name': config_name}) api.add_resource(GetStatRating, "/songs/avg/rating/<string:song_id>", endpoint="get_stat_rating", resource_class_kwargs={'config_name': config_name}) return app
def tearDownClass(cls): """ Drop database after executed all test cases """ with cls.app.app_context(): Song(is_test_mode=1).drop_database() print('DROPPED database')