Esempio n. 1
0
 def entry_point():
     """
     Returns Mason with the controls:
     - revmusic:reviews-all
     - revmusic:albums-all
     - revmusic:users-all
     """
     body = RevMusicBuilder()
     body.add_namespace('revmusic', LINK_RELATIONS_URL)
     body.add_control_reviews_all()
     body.add_control_albums_all()
     body.add_control_users_all()
     return Response(json.dumps(body), 200, mimetype=MASON)
Esempio n. 2
0
    def get(self):
        """
        Responds to GET request with a listing of all user items known to the API (JSON document with added hypermedia controls (MASON))
        """
        body = RevMusicBuilder()
        body.add_namespace('revmusic', LINK_RELATIONS_URL)
        body.add_control_users_all('self')
        body.add_control_reviews_all()
        body.add_control_albums_all()
        body.add_control_add_user()

        body['items'] = []
        for user in User.query.all():
            item = RevMusicBuilder(username=user.username)
            item.add_control('self', url_for('api.useritem',
                                             user=user.username))
            item.add_control('profile', USER_PROFILE)
            body['items'].append(item)

        return Response(json.dumps(body), 200, mimetype=MASON)
Esempio n. 3
0
    def get(self):
        """
        Responds to GET request with a listing of review items known to the API (JSON document with added hypermedia controls (MASON))
        Query parameters in the request URL can be used to filter the returned reviews.
        """
        body = RevMusicBuilder()
        body.add_namespace('revmusic', LINK_RELATIONS_URL)
        body.add_control_reviews_all('self')
        body.add_control_users_all()
        body.add_control_albums_all()

        # Obtain query parameters sent by user
        args = self.parse.parse_args()
        reviews = []
        foreign_keys = []
        timeframe = []
        nlatest = args['nlatest']  # None or int

        if args['timeframe'] is not None:
            try:
                temp = args['timeframe'].split('_')
                if not temp[0][4:].isnumeric() or not temp[0][2:4].isnumeric(
                ) or not temp[0][0:2].isnumeric():
                    return create_error_response(415,
                                                 'Incorrect timeframe format')
                try:
                    datetime.date(int(temp[0][4:]), int(temp[0][2:4]),
                                  int(temp[0][0:2]))
                except ValueError:
                    return create_error_response(415,
                                                 'Incorrect timeframe format')
                timeframe.append('{}-{}-{}'.format(temp[0][4:], temp[0][2:4],
                                                   temp[0][0:2]))
                # Check for possible second time
                if len(temp) is 2:
                    if not temp[1][4:].isnumeric() or not temp[1][
                            2:4].isnumeric() or not temp[1][0:2].isnumeric():
                        return create_error_response(
                            415, 'Incorrect timeframe format')
                    try:
                        datetime.date(int(temp[1][4:]), int(temp[1][2:4]),
                                      int(temp[1][0:2]))
                    except ValueError:
                        return create_error_response(
                            415, 'Incorrect timeframe format')
                    timeframe.append('{}-{}-{}'.format(temp[1][4:],
                                                       temp[1][2:4],
                                                       temp[1][0:2]))
                # Make sure no more than 2 timeframes were provided
                if len(temp) > 2:
                    raise Exception('More than two timeframe parameters')
            except Exception as e:
                # Return an error if an exception occurred
                return create_error_response(
                    415, 'Incorrect timeframe format',
                    'You provided an incorrect timeframe format. Please fix that >:( {}'
                    .format(e))

        # Error handling for nlatest is implemented by flask, since the type has been set to int

        # Handle filtering
        if not args['searchword']:
            # No searchword
            if len(timeframe) < 1:
                # No timeframe provided, return all or nlatest
                reviews = Review.query.order_by(
                    Review.submission_date.desc()).limit(nlatest).all()
            elif len(timeframe) == 1:
                # One time provided, return all or nlatest after that
                reviews = Review.query.filter(func.date(Review.submission_date) >= timeframe[0])\
                    .order_by(Review.submission_date.desc()).limit(nlatest).all()
            else:
                # Two times provided, return all or nlatest between them
                reviews = Review.query.filter(func.date(Review.submission_date) >= timeframe[0])\
                    .filter(func.date(Review.submission_date) <= timeframe[1]).order_by(Review.submission_date.desc()).limit(nlatest).all()

        else:
            # Handle filtering
            if args['filterby'] == 'album':
                foreign_keys = Album.query.filter(
                    Album.title.contains(args['searchword'])).all()
            elif args['filterby'] == 'artist':
                foreign_keys = Album.query.filter(
                    Album.artist.contains(args['searchword'])).all()
            elif args['filterby'] == 'genre':
                foreign_keys = Album.query.filter(
                    Album.genre.contains(args['searchword'])).all()
            else:  # Filter by users
                foreign_keys = User.query.filter(
                    User.username.contains(args['searchword'])).all()

            if len(timeframe) < 1:
                reviews = Review.query.filter(
                    Review.album_id.in_([
                        fk.id for fk in foreign_keys
                    ])).order_by(
                        Review.submission_date.desc()).limit(nlatest).all()
            elif len(timeframe) == 1:
                reviews = Review.query.filter(Review.album_id.in_([fk.id for fk in foreign_keys])).filter(func.date(Review.submission_date) >= timeframe[0])\
                    .order_by(Review.submission_date.desc()).limit(nlatest).all()
            else:
                reviews = Review.query.filter(Review.album_id.in_([fk.id for fk in foreign_keys])).filter(func.date(Review.submission_date) >= timeframe[0])\
                    .filter(func.date(Review.submission_date) <= timeframe[1]).order_by(Review.submission_date.desc()).limit(nlatest).all()

        body['items'] = []
        for review in reviews:
            item = RevMusicBuilder(identifier=review.identifier,
                                   user=review.user.username,
                                   album=review.album.title,
                                   title=review.title,
                                   star_rating=review.star_rating,
                                   submission_date=datetime.datetime.strftime(
                                       review.submission_date,
                                       '%Y-%m-%d %H:%M:%S'))
            item.add_control(
                'self',
                url_for('api.reviewitem',
                        album=review.album.unique_name,
                        review=review.identifier))
            item.add_control('profile', REVIEW_PROFILE)
            body['items'].append(item)
        return Response(json.dumps(body), 200, mimetype=MASON)