Beispiel #1
0
def recreate_database():
    Song.collection().drop()
    Rating.collection().drop()
    Song.insert_many(songs_from_json())

    Song.collection().create_index([
        ('artist', TEXT),
        ('title', TEXT),
    ])
Beispiel #2
0
def songs_avg_difficulty():
    id = 'all songs'
    pipelines = []
    try:
        level = request.args['level']
        pipelines.append({
            '$match': {
                'level': int(
                    level
                ),  # TODO: deserialise all inputs so there's no need to cast to int here
            }
        })
        id = f'level {level} songs'
    except KeyError:  # No level
        pass

    pipelines.append({
        '$group': {
            '_id': id,
            'average_difficulty': {
                '$avg': '$difficulty'
            },
        },
    })
    try:
        result = next(Song.collection().aggregate(pipeline=pipelines))
    except StopIteration:
        result = dict(
            _id='Database is empty',
            average_difficulty=None,
        )
    return jsonify(result)
Beispiel #3
0
def songs_search():
    try:
        message = request.args['message']
    except KeyError:
        message = ''

    try:
        # TODO: if/when partial matches are required and/or performance becomes an issue, refactor to use elasticsearch
        result = list(Song.collection().aggregate(pipeline=[{
            '$match': {
                '$text': {
                    '$search': message
                },
            },
        }]))
        results = Song.Schemas.Get(many=True).dump(result)
    except OperationFailure as e:
        if "no such collection 'homework.songs'" not in e._message:
            raise e
        results = []
    return jsonify(dict(results=results, ))