Пример #1
0
 def createReviewViaPeewee(self):
     record = Review(
         message='foo-message',
         user=2,
         stars=5
     )
     record.save()
     return record
Пример #2
0
 def tearDown(self):
     """Remove tables from airbnb_test database upon completion of test."""
     ReviewUser.drop_table()
     ReviewPlace.drop_table()
     Review.drop_table()
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
Пример #3
0
def add_review(book_id):
    review = request.args.get('review')
    print(f"Review: {review}")
    book = Book.query.filter_by(id=book_id).first()
    if review == "":
        return redirect(url_for('book.book_detail', book_id=book_id, message=bid_message_03))
    # If book is owned by the current user show  watchlist_message_01
    if current_user.id == int(book.user_id):
        return redirect(url_for('book.book_detail', book_id=book_id, message=bid_message_01))
    # If book is not owned by the current user.
    else:
        review = Review(current_user.id, book_id, review)
        result = review.add_review()
        return redirect(url_for('book.book_detail', book_id=book_id, message=bid_message_02))
Пример #4
0
def place_review(place_id, review_id):
	query = ReviewPlace.select().where(ReviewPlace.review == review_id, ReviewPlace.place == place_id)

	if query.wrapped_count() < 1:
		return json_response(status_=404, msg="not found")

	if request.method == "GET":
		query = Review.get(Review.id == review_id)
		return jsonify(query.to_dict()), 200

	elif request.method == "DELETE":
		ReviewPlace.delete().where(ReviewPlace.review == review_id, ReviewPlace.place == place_id).execute()
		Review.delete().where(Review.id == review_id).execute()
		return json_response(status_=200, msg="review delete")
Пример #5
0
def get_reviews_user(user_id):
    # Checking if an user exist
    try:
        User.get(User.id == user_id)
    except User.DoesNotExist:
        return jsonify(msg="There is no user with this id."), 404

    # Getting all the review by user id
    if request.method == "GET":
        try:
            # Checking if a review exist on a specific user
            try:
                ReviewUser.get(ReviewUser.user == user_id)
            except:
                return jsonify(
                    msg="There is no review for an user with this id."), 404
            # retriving the reviews an user received
            list = ListStyle.list(
                User.select().join(ReviewUser).where(
                    ReviewUser.user == User.id).where(
                        ReviewUser.user == user_id), request)
            return jsonify(list)
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)

    elif request.method == "POST":
        user_message = request.form["message"]
        user_stars = request.form["stars"]

        try:
            new_review = Review(message=user_message,
                                stars=user_stars,
                                user=user_id)
            new_review.save()

            user_review = ReviewUser(user=user_id, review=new_review.id)
            user_review.save()

            return jsonify(new_review.to_dict())
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
Пример #6
0
def handle_reviews(user_id):
    '''Returns the reviews of the user passed the argument `user_id`. This is
    accomplished through querying the ReviewUser table, and returning rows in
    which `user_id` is equal to the id of a user. Then, using the
    ForeignKeyField, retrieve those particular reviews with the to_dict()
    method. Will not add attributes `updated_at` or `created_at`. Note: this
    route is for reviewing the user with id `user_id`. The user id passed as
    a parameter with a POST request is the user making the review.

    Keyword arguments:
    user_id = The id of the user that is being reviewed.
    '''
    try:
        User.select().where(User.id == user_id).get()
    except User.DoesNotExist:
        return jsonify(msg="There is no user with this id."), 404

    if request.method == 'GET':
        arr = []
        for review_user in (ReviewUser
                            .select()
                            .where(ReviewUser.user == user_id)):
            arr.append(review_user.review.to_dict())
        return jsonify(arr), 200

    elif request.method == 'POST':
        params = request.values
        review = Review()

        '''Check that all the required parameters are made in request.'''
        required = set(["message", "user"]) <= set(request.values.keys())
        if required is False:
            return jsonify(msg="Missing parameter."), 400

        for key in params:
            if key == 'updated_at' or key == 'created_at':
                continue
            setattr(review, key, params.get(key))

        if review.message is None or review.user_id is None:
            return jsonify(msg="Missing required data."), 404

        review.save()

        '''Save the connection in the ReviewUser table.'''
        ReviewUser().create(user=user_id, review=review.id)

        return jsonify(review.to_dict()), 201
Пример #7
0
def delete_place_review(place_id, review_id):
	"""
    Delete the given place review
    Deletes the given place review in the database.
    ---
    tags:
        - Review
    parameters:
        -
            in: path
            name: place_id
            type: integer
            required: True
            description: ID of the place reviewed
		-
            in: path
            name: review_id
            type: integer
            required: True
            description: ID of the review
    responses:
        200:
            description: Place review deleted successfully
            schema:
                $ref: '#/definitions/delete_amenity_delete_delete_200'
        404:
            description: Place or user was not found
        500:
            description: Request could not be processed
    """
	try:
		query = ReviewPlace.select().where(ReviewPlace.review == review_id, ReviewPlace.place == place_id)
		if not query.exists():
			raise LookupError('Not found')
		query = Review.select().where(Review.id == review_id)
		if not query.exists():
			raise LookupError('Not found')
		ReviewPlace.delete().where(ReviewPlace.review == review_id, ReviewPlace.place == place_id).execute()
		Review.delete().where(Review.id == review_id).execute()
		res = {
			'code': 200,
			'msg': 'Review deleted successfully'
		}
		return res, 200
	except LookupError as e:
		abort(404)
	except Exception as e:
		print e
Пример #8
0
    def subtest_createWithAllParams_proute(self):
        """
        Test proper creation of a place review record upon POST request to the
        API with all parameters provided.
        """
        # create records with POST; check for success
        # ----------------------------------------------------------------------
        POST_request = self.app.post('/places/1/reviews', data=dict(
            message='foo-message',
            user_id=2,
            stars=5
        ))
        self.assertEqual(POST_request.status[:3], '200')

        # validate values stored in db
        # ----------------------------------------------------------------------
        # for review record
        now = datetime.now().strftime('%d/%m/%Y %H:%M')
        record = Review.get(Review.id == 1)

        self.assertEqual(record.message, 'foo-message')
        self.assertEqual(record.user.id, 2)
        self.assertEqual(record.stars, 5)
        self.assertEqual(record.created_at.strftime('%d/%m/%Y %H:%M'), now)
        self.assertEqual(record.updated_at.strftime('%d/%m/%Y %H:%M'), now)

        # for review place record
        now = datetime.now().strftime('%d/%m/%Y %H:%M')
        record = ReviewPlace.get(ReviewPlace.review == 1)

        self.assertEqual(record.place.id, 1)
Пример #9
0
def post_review(user_id):
    post_data = request.values
    if 'message' not in post_data or 'user_id' not in post_data:
    	return {"code": 400, "msg":"bad request, incomplete parameters"}, 400
    try:
    	user_to_query = User.get(User.id == user_id)
    except:
    	return {"code": 404, "msg":"to_user does not exist"}, 404

    review_dictionary = review_dict(
    	post_data['message'],
    	post_data['user_id'],
    	post_data.get('stars'),
    )

    new_review, created = Review.create_or_get(**review_dictionary)
    if not created:
    	return {"code": 404, "msg":"from_user does not exist"}, 404
    new_reviewUser, created = ReviewUser.create_or_get(
    	user = user_id,
    	review = new_review,
    )
    if not created:
    	return {"code": 404, "msg":"bad request"}, 404
    return new_review.to_dict()
Пример #10
0
    def test_create_proute(self):
        """
        Test proper creation (or non-creation) of place review records upon
        POST requests to API.
        """
        # test response to POST request to place ID which does not exist
        # ----------------------------------------------------------------------
        xPOST_request = self.app.post('/place/1000/reviews', data=dict(
            message='foo-message',
            user_id=2,
            stars=5
        ))
        self.assertEqual(xPOST_request.status[:3], '404')

        # test creation of review with all parameters provided in POST request
        # ----------------------------------------------------------------------
        self.subtest_createWithAllParams_proute()

        # test that review ID for sole record in database is correct
        # ----------------------------------------------------------------------
        self.assertEqual(Review.select().get().id, 1)

        # test creatxn of review in all cases of parameter missing in POST req.
        # ----------------------------------------------------------------------
        self.subtest_createWithoutAllParams_proute()
Пример #11
0
    def add_review(data, business_id, user_id):
        """ add a review to a business """

        if "text" not in data:
            return jsonify({
                "success": False,
                "message": "Provide a review ('text')"
            }), 400

        # check if business id exists
        business_result = BS.check_business(business_id)
        if not business_result["success"]:
            return jsonify({
                "success":
                False,
                "message":
                "Business with id " + business_id + " not found"
            }), 404

        Review(text=data["text"], business_id=business_id,
               user_id=user_id).add_review()

        return jsonify({
            "success": True,
            "message": "Review posted successfully"
        }), 201
Пример #12
0
def delete_reviews_user(user_id, review_id):
    # Checking if the review exist
    try:
        get_review = (
            ReviewUser.select().where((ReviewUser.review == review_id)
                                      & (ReviewUser.user == user_id)).get())

    except:
        return make_response(
            jsonify({
                'code': 10000,
                'msg': 'Review not found'
            }), 404)
    if request.method == 'GET':
        # getting the review with the id review and user id
        return jsonify(get_review.review.to_dict())

    elif request.method == 'DELETE':
        try:
            user_review = ReviewUser.get((ReviewUser.user == user_id)
                                         & (ReviewUser.review == review_id))
            user_review.delete_instance()

            get_review = Review.get(Review.id == review_id)
            get_review.delete_instance()
            return "Review was deleted"
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
Пример #13
0
 def create_with_user(self, db: Session, user: User,
                      review_data: ReviewCreateSchema) -> Review:
     review = Review(**review_data.dict())
     user.reviews.append(review)  # type: ignore
     db.add(review)
     db.commit()
     db.refresh(review)
     return review
Пример #14
0
def create_user_reviews(user_id):
    """
    Create User Reviews of user with id as user_id
    """
    data = request.form
    try:
        if not data['user_id']:
            raise KeyError('user_id')
        elif not data['message']:
            raise KeyError('message')
        elif not isinstance(data['message'], unicode):
            raise ValueError('message')
        query = User.select().where(User.id == user_id)
        if not query.exists():
            raise LookupError('user_id')
        query = User.select().where(User.id == data['user_id'])
        if not query.exists():
            raise LookupError('from_user_id')
        new_review = Review(user_id=data['user_id'], message=data['message'])
        if 'stars' in data:
            new_review.stars = data['stars']
        new_review.save()
        new_user_review = ReviewUser.create(user=user_id, review=new_review.id)
        res = {}
        res['code'] = 201
        res['msg'] = 'Review was saved successfully'
        res['id'] = new_review.id
        return res, 201
    except KeyError as e:
        res = {}
        res['code'] = 40000
        res['msg'] = 'Missing parameters'
        return res, 400
    except ValueError as e:
        res = {}
        res['code'] = 400
        res['msg'] = str(e.message) + ' is invalid'
        return res, 400
    except LookupError as e:
        abort(404)
    except Exception as e:
        res = {}
        res['code'] = 500
        res['msg'] = e.message
        return res, 500
Пример #15
0
def delete_place_review(place_id, review_id):
    try:
        query = ReviewPlace.select().where(ReviewPlace.review == review_id,
                                           ReviewPlace.place == place_id)
        if not query.exists():
            raise LookupError('Review not found')
        query = Review.select().where(Review.id == review_id)
        if not query.exists():
            raise LookupError('Review not found')
        ReviewPlace.delete().where(ReviewPlace.review == review_id,
                                   ReviewPlace.place == place_id).execute()
        Review.delete().where(Review.id == review_id).execute()
        res = {'code': 200, 'msg': 'Review was deleted successfully'}
        return res, 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        return e, 409
Пример #16
0
def all_reviews():
    try:
        query = Review.select()
        return ListStyles.list(query, request), 200
    except:
        return jsonify({
            'code': 404,
            'msg': "table does not yet exist in db"
        }), 404
Пример #17
0
def user_review(user_id, review_id):
	user_test = User.select().where(User.id == user_id)

	if user_test.wrapped_count() < 1:
		return json_response(status_=404, msg="user does not exist with that id")

	review = Review.select().where(Review.id == review_id, Review.user == user_id)

	if review.wrapped_count() < 1:
		return json_response(status_=404, msg="no review with that id for user with selected id")

	if request.method == "GET":
		review = Review.get(Review.id == review_id, Review.user == user_id)
		return jsonify(review.to_dict()), 200

	elif request.method == "DELETE":
		ReviewUser.delete().where(ReviewUser.user == user_id, ReviewUser.review == review_id).execute()
		Review.delete().where(Review.id == review_id, Review.user == user_id).execute()
		return json_response(status_=200, msg="review deleted")
Пример #18
0
def delete_review(user_id, review_id):
	try:
		rev_query2 = ReviewUser.select().where(ReviewUser.user == user_id, ReviewUser.review == review_id).get()
		rev_query = Review.select().join(ReviewUser).where(ReviewUser.user == user_id, Review.id == review_id).get()
	except:
		return {"code": 400, "msg":"Bad request"}, 400
	out_dict = rev_query.to_dict()
	rev_query2.delete_instance()
	rev_query.delete_instance()
	return out_dict
Пример #19
0
def handle_place_reviews(place_id):
    '''Returns an array of reviews of the place with the same id as that of
    the parameter `place_id` with a GET request. Creates a new review with
    the place_id with a POST request. Will not add attributes `updated_at` or
    `created_at`.

    Keyword arguments:
    place_id -- The id of the place to be reviewed.
    '''
    try:
        Place.select().where(Place.id == place_id).get()
    except Place.DoesNotExist:
        return jsonify(msg="Place does not exist."), 404

    if request.method == 'GET':
        arr = []
        for review_place in (ReviewPlace
                             .select()
                             .where(ReviewPlace.place == place_id)):
            arr.append(review_place.review.to_dict())
        return jsonify(arr), 200

    elif request.method == 'POST':
        params = request.values
        review = Review()

        '''Check that all the required parameters are made in request.'''
        required = set(["message", "user"]) <= set(request.values.keys())
        if required is False:
            return jsonify(msg="Missing parameter."), 400

        for key in params:
            if key == 'updated_at' or key == 'created_at':
                continue
            setattr(review, key, params.get(key))

        review.save()

        '''Save the connection in the ReviewPlace table.'''
        ReviewPlace().create(place=place_id, review=review.id)

        return jsonify(review.to_dict()), 201
Пример #20
0
def user_reviews(user_id):
    """Handle GET and POST requests to /users/<user_id>/reviews route.

    Return a list of all reviews for given user in the database in the case of
    a GET request.
    Create a new user review in the database in the case of a POST request.
    """
    # check whether user resource exists:
    # --------------------------------------------------------------------------
    try:
        record = User.get(User.id == user_id)

    # return 404 not found if it does not
    except User.DoesNotExist:
        return json_response(
            add_status_=False,
            status_=404,
            code=404,
            msg="not found"
        )

    # if exception does not arise:
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = []
        for record in ReviewUser.select().where(ReviewUser.user == user_id):
            hash = record.review.to_hash()
            list.append(hash)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':

        if "stars" in request.form.keys():
            record = Review(
                message=request.form["message"],
                user=request.form["user_id"],
                stars=request.form["stars"]
            )

        else:
            record = Review(
                message=request.form["message"],
                user=request.form["user_id"]
            )

        record.save()

        u_review = ReviewUser(
            user=user_id,
            review=record.id
        )
        u_review.save()

        return jsonify(record.to_hash())
Пример #21
0
def user_reviews_id(user_id, review_id):
    try:
        query_one = ReviewUser.select().where(
            ReviewUser.user == user_id, ReviewUser.review == review_id).get()
    except:
        return jsonify({
            "code":
            404,
            "msg":
            "record does not exist in db, check user id and review id"
        }), 404

    if request.method == "GET":
        query = Review.get(Review.id == review_id)
        return jsonify(query.to_dict()), 200
    elif request.method == "DELETE":
        query_two = Review.get(Review.id == review_id)
        query_one.delete_instance()
        query_two.delete_instance()
        return jsonify({"code": 200, "msg": "success"}), 200
Пример #22
0
def delete_all_reviews_by_place(place_id, review_id):
	try:
		query = ReviewPlace.select().where(ReviewPlace.place == place_id).get()
		review_query = Review.select().join(ReviewPlace).where(ReviewPlace.place == place_id, Review.id == review_id).get()
	except:
		return {'code': 400, 'msg': 'Bad Request'}, 400
    
	out_dict = review_query.to_dict()
	query.delete_instance()
	review_query.delete_instance()
	return out_dict
Пример #23
0
def review_business(id):

    # get auth token
    auth_header = request.headers.get('Authorization')

    if len(auth_header.split(" ")) > 1:
        auth_token = auth_header.split(" ")[1]

    user_id = User.get_token_user_id(auth_token)

    #check if token exists in the Token table
    token = Token.query.filter_by(token=auth_token).first()

    #try to see if you can get a user by a token
    # they are identified with
    if token is None:
        return make_response(
            jsonify({
                "message": "Invalid Token",
                "status": "failure"
            })), 403

    #check if business is there
    business = Business.query.get(id)

    #check if the user id from the decoded token exists in the db
    user = User.query.get(int(user_id))

    if business is None:
        return make_response(
            jsonify({
                "message": 'Business was not found',
                "status": "failure"
            })), 404

    # get the data that was sent in the request
    data = request.get_json()

    #create review object
    new_review = Review(review_summary=data['review_summary'],
                        review_description=data['review_description'],
                        star_rating=data['star_rating'],
                        creator=user,
                        business=business)

    #add review to the database

    db.session.add(new_review)
    db.session.commit()

    message = "Created review: " + new_review.review_summary + "successfuly"
    response = {"message": message, "status": "success"}

    return make_response(jsonify(response)), 201
Пример #24
0
def add_review(content, username, movieId, repo):
    user = repo.get_user(username)
    if user is None:
        raise UserNotFoundException

    movie = repo.get_movie(movieId)
    if movie is None:
        raise MovieNotFoundException

    timestamp = datetime.now()
    repo.add_review(Review(content, timestamp, user, movie))
Пример #25
0
def delete_user_review(user_id, review_id):
    """
    Delete User Reviews of user with id as user_id
    and review with id as reveiw_id
    """
    try:
        query = ReviewUser.select().where(ReviewUser.review == review_id,
                                          ReviewUser.user == user_id)
        if not query.exists():
            return {'code': 404, 'msg': 'Review not found'}, 404
        query = Review.select().where(Review.id == review_id)
        if not query.exists():
            return {'code': 404, 'msg': 'Review not found'}, 404
        ReviewUser.delete().where(ReviewUser.review == review_id,
                                  ReviewUser.user == user_id).execute()
        Review.delete().where(Review.id == review_id).execute()
        res = {'code': 200, 'msg': 'Review was deleted successfully'}
        return res, 200
    except Exception as e:
        res = {'code': 500, 'msg': e.message}
        return res, 500
Пример #26
0
def handle_my_reviews(user_id):
    '''Returns all the reviews from the database of the user as JSON objects
    with a GET request.

    Keyword Arguments:
    user_id = The id of the user that wrote the review.
    '''
    if request.method == 'GET':
        arr = []
        for review in Review.select().where(Review.user == user_id):
            arr.append(review.to_dict())
        return jsonify(arr), 200
Пример #27
0
def get_user_reviews(user_id):
	"""
	Get all user reviews
	List all user reviews in the database.
	---
	tags:
	    - Review
	parameters:
		-
			in: path
			name: user_id
			type: string
			required: True
			description: ID of the user
	responses:
	    200:
	        description: List of all user reviews
	        schema:
	            id: UserReviews
	            required:
	                - data
	                - paging
	            properties:
	                data:
	                    type: array
	                    description: user reviews array
	                    items:
	                        $ref: '#/definitions/get_user_review_get_UserReview'
	                paging:
	                    description: pagination
	                    schema:
	                        $ref: '#/definitions/get_amenities_get_Paging'
	"""
	try:
		''' Test if user_id exists '''
		query = User.select().where(User.id == user_id)
		if not query.exists():
			raise LookupError('user_id')

		''' Get list of reviews for the user and return response '''
		reviews = Review.select(Review, ReviewUser).join(ReviewUser).where(ReviewUser.user == user_id)
		return ListStyle.list(reviews, request), 200
	except LookupError as e:
		abort(404)
	except Exception as e:
		print e.message
		res = {
			'code': 500,
			'msg': e.message
		}
		return res, 500
Пример #28
0
def delete_reviews_place(place_id, review_id):
    try:
        # Checking if place exist
        Place.select().where(Place.id == place_id).get()
    except Place.DoesNotExist:
        return make_response(jsonify({'code': 10000, 'msg': 'Not found'}), 404)
    if request.method == 'GET':
        try:
            # Checking if a review exist
            Review.get(Review.id == review_id)
            # Getting the review for a place
            list = ListStyle.list(
                Review.select().join(ReviewPlace).where(
                    ReviewPlace.review == Review.id).where(
                        ReviewPlace.place == place_id
                        and ReviewPlace.review == review_id), request)
            return jsonify(list)
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
    elif request.method == 'DELETE':
        try:
            place_review = (ReviewPlace.get(ReviewPlace.place == place_id
                                            & ReviewPlace.review == review_id))
            place_review.delete_instance()

            get_review = Review.get(Review.id == review_id)
            get_review.delete_instance()
            return "Review was deleted"
        except:
            return make_response(
                jsonify({
                    'code': 10000,
                    'msg': 'Review not found'
                }), 404)
Пример #29
0
def get_place_reviews(place_id):
    try:
        query = Place.select().where(Place.id == place_id)
        if not query.exists():
            raise LookupError('place_id')
        reviews = Review.select(
            Review,
            ReviewPlace).join(ReviewPlace).where(ReviewPlace.place == place_id)
        return ListStyle.list(reviews, request), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        res = {'code': 500, 'msg': e.message}
        return res, 500
Пример #30
0
def handle_review_id(user_id, review_id):
    '''Gets the review with the id of the parameter `review_id`.

    Keyword arguments:
    user_id -- The id of the user with the review.
    review_id -- The id of the the review.
    '''
    try:
        this_review = ReviewUser.select().where(
                        (ReviewUser.user == user_id) &
                        (ReviewUser.review == review_id)).get()
    except ReviewUser.DoesNotExist:
        return jsonify(msg="Review does not exist."), 404

    if request.method == 'GET':
        return jsonify([this_review.review.to_dict()]), 200

    elif request.method == 'DELETE':
        ReviewUser.delete().where((ReviewUser.user == user_id) &
                                  (ReviewUser.review == review_id)).execute()

        Review.delete().where(Review.id == review_id).execute()
        return jsonify(msg="Review deleted successfully."), 200
Пример #31
0
def get_user_review(user_id, review_id):
    """
    Create User Reviews of user with id as user_id
    and review with id as reveiw_id
    """
    try:
        query = ReviewUser.select().where(ReviewUser.review == review_id,
                                          ReviewUser.user == user_id)
        query = Review.get(Review.id == review_id)
        data = query.to_dict()
        data['touserid'] = user_id
        return data, 200
    except Exception:
        return {'code': 404, 'msg': 'Review not found'}, 404
Пример #32
0
def get_place_review(place_id, review_id):
    try:
        query = ReviewPlace.select().where(ReviewPlace.review == review_id,
                                           ReviewPlace.place == place_id)
        if not query.exists():
            raise LookupError('Review not found')
        query = Review.get(Review.id == review_id)
        data = query.to_dict()
        data['toplaceid'] = place_id
        return data, 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        return e, 409
Пример #33
0
def review_place_id(place_id, review_id):
    """Handle GET and DELETE requests to /places/<place_id>/reviews/<review_id>.

    Return a hash representing place review in the case of a GET request.
    Delete appropriate records for place review in case of DELETE request.
    """
    # check whether place resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Place.get(Place.id == place_id)

    # return 404 not found if it does not
    except Place.DoesNotExist:
        return json_response(
            add_status_=False,
            status_=404,
            code=404,
            msg="not found"
        )

    # if exception does not arise:

    # check whether review resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Review.get(Review.id == review_id)

    # return 404 not found if it does not
    except Review.DoesNotExist:
        return json_response(
            add_status_=False,
            status_=404,
            code=404,
            msg="not found"
        )

    # if exception does not arise:
    # --------------------------------------------------------------------------
    # handle GET requests
    if request.method == 'GET':
        return jsonify(record.to_hash())

    # handle DELETE requests
    elif request.method == "DELETE":
        pr_record = ReviewPlace.get(ReviewPlace.review == review_id)
        pr_record.delete_instance()
        pr_record.save()
        record.delete_instance()
        record.save()
        return 'deleted review record\ndeleted review place record\n'
Пример #34
0
def review_user_id(user_id, review_id):
    """Handle GET and DELETE requests to /users/<user_id>/reviews/<review_id>.

    Return a hash representing user review in the case of a GET request.
    Delete appropriate records for user review in case of DELETE request.
    """
    # check whether user resource exists:
    # --------------------------------------------------------------------------
    try:
        record = User.get(User.id == user_id)

    # return 404 not found if it does not
    except User.DoesNotExist:
        return json_response(
            add_status_=False,
            status_=404,
            code=404,
            msg="not found"
        )

    # if exception does not arise:

    # check whether review resource exists:
    # --------------------------------------------------------------------------
    try:
        record = Review.get(Review.id == review_id)

    # return 404 not found if it does not
    except Review.DoesNotExist:
        return json_response(
            add_status_=False,
            status_=404,
            code=404,
            msg="not found"
        )

    # if exception does not arise:
    # --------------------------------------------------------------------------
    # handle GET requests
    if request.method == 'GET':
        return jsonify(record.to_hash())

    # handle DELETE requests
    elif request.method == "DELETE":
        ur_record = ReviewUser.select().where(ReviewUser.review == review_id).get()
        ur_record.delete_instance()
        ur_record.save()
        record.delete_instance()
        record.save()
        return 'deleted review record\ndeleted review user record\n'
Пример #35
0
def test_add_review(session_factory):
    repo = SqlAlchemyRepository(session_factory)

    movieId = 1
    movie = repo.get_movie(movieId)

    user = make_user()
    repo.add_user(user)

    timestamp = datetime(2020, 10, 1)
    review = Review('first review', timestamp, user, movie)
    repo.add_review(review)

    assert len(movie.reviews) == 1
    assert review in movie.reviews
Пример #36
0
def user_reviews(user_id):
	user_test = User.select().where(User.id == user_id)

	if user_test.wrapped_count() < 1:
		return json_response(status_=404, msg="user does not exist with that id")

	if request.method == "GET":
		query = ReviewUser.select().where(ReviewUser.user == user_id) 

		return ListStyle.list(query, request), 200


	elif request.method == "POST":
		if "message" not in request.form:
			return json_response(status_=400, code=40000, msg="missing parameters")

		elif "user_id" not in request.form:
			return json_response(status_=400, code=40000, msg="missing parameters")

		elif "stars" not in request.form:
			review = Review(message=str(request.form["message"]), user=request.form["user_id"])
			review.save()

			u_review = ReviewUser(user=user_id, review=review.id)
			u_review.save()

			return jsonify(review.to_dict()), 201

		else:
			review = Review(message=str(request.form["message"]), user=request.form["user_id"], stars=int(request.form["stars"]))
			review.save()

			u_review = ReviewUser(user=user_id, review=review.id)
			u_review.save()

			return jsonify(review.to_dict()), 201
Пример #37
0
def get_user_reviews(user_id):
    """
    Get user Reviews of user with id as user_id
    """
    try:
        query = User.select().where(User.id == user_id)
        if not query.exists():
            raise LookupError('user_id')
        reviews = Review.select(
            Review,
            ReviewUser).join(ReviewUser).where(ReviewUser.user == user_id)
        return ListStyle.list(reviews, request), 200
    except LookupError as e:
        abort(404)
    except Exception as e:
        res = {'code': 500, 'msg': e.message}
        return res, 500
Пример #38
0
def post_review_by_place(place_id):
	post_data = request.values
	if 'message' not in post_data or 'user_id' not in post_data:
		return {"code": 400, "msg":"bad request, incomplete parameters"}, 400
	try:
		place_get = Place.get(Place.id == place_id)
	except Place.DoesNotExist:
		return {'code': 10004, 'msg': 'Place does not exist'}, 404
	review_dictionary = review_dict(
    	post_data['message'],
    	post_data['user_id'],
    	post_data.get('stars'),
    )

	new_review, created = Review.create_or_get(**review_dictionary)
	if not created:
		return {'code': 404, 'msg': 'User does not exist'}, 404
	new_review_place = ReviewPlace.create(place=place_id, review=new_review)
	return new_review.to_dict()
Пример #39
0
def test_review(empty_session):
    movie = make_movie()
    empty_session.add(movie)
    empty_session.commit()

    user = User('jack', '123456')
    empty_session.add(user)
    empty_session.commit()

    review_date = datetime(year=2020, month=10, day=10)
    review = Review('first review', review_date, user, movie)
    empty_session.add(review)
    empty_session.commit()

    assert review in movie.reviews

    result = empty_session.execute('select user_id, movie_id from reviews where id = :id', {'id':review.id}).fetchone()
    assert result[0] == user.id
    assert result[1] == movie.id
Пример #40
0
def add_review():
    try:
        data = request.data
        review_data = json.loads(data.decode("utf-8"))
        for recipe in Recipe.query.filter(Recipe.id == review_data['id']):
            review = Review(credit=replacer(review_data['credit']),
                            text=replacer(review_data['text']),
                            approved=False)
            db_session.add(review)
            recipe.reviews.append(review)
        db_session.commit()
        clear_sessions()
        return return_result(data="added review for recipe with id: " +
                             review_data['id'])
    except IndexError:
        clear_sessions()
        return return_result(message="This recipe index does not exist",
                             code=400,
                             status="failure")
Пример #41
0
def get_place_review(place_id, review_id):
	"""
	Get the given place review
	Returns the given place review in the database.
	---
	tags:
		- Review
	parameters:
		-
			in: path
			name: place_id
			type: string
			required: True
			description: ID of the place
		-
			in: path
			name: review_id
			type: string
			required: True
			description: ID of the review
	responses:
	    200:
	        description: Place review returned successfully
	        schema:
	            id: PlaceReview
	            required:
	                - fromuserid
	                - message
	                - toplaceid
	                - id
	                - created_at
	                - updated_at
	            properties:
	                message:
	                    type: string
	                    description: message of the review
	                    default: 'Super awesome!'
	                stars:
	                    type: integer
	                    description: number of stars given on review
	                    default: 5
	                fromuserid:
	                    type: integer
	                    description: id of the user giving the review
	                    default: 1
	                touserid:
	                    type: integer
	                    description: id of the user receiving the review
	                    default: None
	                toplaceid:
	                    type: integer
	                    description: id of the place receiving the review
	                    default: 1
	                id:
	                    type: integer
	                    description: id of the review
	                    default: 1
	                created_at:
	                    type: datetime string
	                    description: date and time the review was created in the database
	                    default: '2016-08-11 20:30:38'
	                updated_at:
	                    type: datetime string
	                    description: date and time the review was updated in the database
	                    default: '2016-08-11 20:30:38'
	    404:
	        description: Review, user or place was not found
	    500:
	        description: Request could not be processed
    """
	try:
		query = ReviewPlace.select().where(ReviewPlace.review == review_id, ReviewPlace.place == place_id)
		if not query.exists():
			raise LookupError('Not found')
		query = Review.get(Review.id == review_id)
		data = query.to_dict()
		data['toplaceid'] = place_id
		return data, 200
	except LookupError as e:
		abort(404)
	except Exception as e:
		print e
Пример #42
0
def create_user_reviews(user_id):
	"""
	Create a new user review
	Create a new review for the given user in the database
	---
	tags:
	    - Review
	parameters:
	    -
	        name: user_id
	        in: path
	        type: integer
	        required: True
	        description: id of the user being reviewed
	    -
	        name: user_id
	        in: form
	        type: integer
	        required: True
	        description: id of the user giving the review
	    -
	        name: message
	        in: form
	        type: string
	        required: True
	        description: the text of the review
	    -
	        name: stars
	        in: form
	        type: integer
	        description: number of stars given on the review
	responses:
	    201:
	        description: User review was created
	        schema:
	            $ref: '#/definitions/create_amenity_post_post_success'
	    400:
	        description: Issue with user review request
	    404:
	        description: A user was not found
	    500:
	        description: The request was not able to be processed
	"""
	data = {}
	for key in request.form.keys():
		for value in request.form.getlist(key):
			data[key] = value
	try:
		''' Test for required data '''
		if not data['user_id']:
			raise KeyError('user_id')
		elif not data['message']:
			raise KeyError('message')

		''' Test type of submitted data '''
		if not type_test(data['user_id'], int):
			raise ValueError('user_id')
		elif not type_test(data['message'], 'string'):
			raise ValueError('message')
		elif 'stars' in data and not type_test(data['stars'], int):
			raise ValueError('stars')

		''' Test if route user_id exists '''
		query = User.select().where(User.id == user_id)
		if not query.exists():
			raise LookupError('user_id')

		''' Test if data user_id exists '''
		query = User.select().where(User.id == data['user_id'])
		if not query.exists():
			raise LookupError('from_user_id')
		''' Create user Review and ReviewUser records'''
		new_review = Review(
			user_id = data['user_id'],
			message = data['message']
		)
		if 'stars' in data:
			new_review.stars = data['stars']
		new_review.save()
		new_user_review = ReviewUser.create(
			user = user_id,
			review = new_review.id
		)
		res = {}
		res['code'] = 201
		res['msg'] = 'Review saved successfully'
		res['id'] = new_review.id
		return res, 201
	except KeyError as e:
		res = {}
		res['code'] = 40000
		res['msg'] = 'Missing parameters'
		return res, 400
	except ValueError as e:
		res = {}
		res['code'] = 400
		res['msg'] = str(e.message) + ' is invalid'
		return res, 400
	except LookupError as e:
		abort(404)
	except Exception as e:
		res = {}
		res['code'] = 500
		res['msg'] = e.message
		print res
		return res, 500
Пример #43
0
def email_a_review():
    current_app.logger.debug('emailing review for a draft')

    if 'did' in request.form and 'uid' in request.form and 'email' in request.form:

        did = request.form['did']
        uid = request.form['uid']
        email = request.form['email']

        draft = Draft.query.filter_by(did=did).first()

        if not draft or draft.uid != g.user.uid:
            return jsonify(error="Invalid draft"), 400

        if not validate_email(email, check_mx=True):
            return jsonify(error="Invalid email"), 400

        # create review pointing to the draft
        review = Review()
        review.did = draft.did
        review.email = email

        # really good code to generate a unique url hash for the review
        unique_hash = False
        gen_hash = ''
        while not unique_hash:
            gen_hash = uuid.uuid4().hex
            queried_review = Review.query.filter_by(urlhash=gen_hash).first()
            if not queried_review:
                unique_hash = True

        review.urlhash = gen_hash

        db.session.add(review)

        # if the draft was not finalized, finalize it and create a new one
        new_did = None
        new_version = None
        new_timestamp = None
        if not draft.finalized:
            draft.finalized = True
            db.session.add(draft)
            db.session.flush()

            # make a new draft for the writer
            new_draft = Draft.next_draft(draft)
            db.session.add(new_draft)
            db.session.flush()

            new_did = new_draft.did
            new_version = new_draft.version
            new_timestamp = new_draft.pretty_modified_date()
        else:
            db.session.flush()

        review_url = 'http://' + app.config.get('SERVER_HOST') + '/essays/review/' + review.urlhash

        # send emailz
        params = {
            'sender': g.user.first_name + ' ' + g.user.last_name,
            'review_url': review_url
        }
        mailer = Mailer()
        mailer.send(ReviewADraft(), params, email)


        # create notification for user receiving review if necessary
        receiving_user = User.query.filter_by(email=email).first()
        if receiving_user:
            notification = Notification()
            notification.uid = receiving_user.uid
            notification.from_uid = uid
            notification.short_template = 'requested a review.'
            notification.url = review_url
            notification.long_template = '{{ sender }} wrote an essay and wants you to <a href="' + review_url +'"> review </a> it.'
            db.session.add(notification)

        db.session.commit()

        return jsonify(status='success',
            new_did=new_did,
            new_version=new_version,
            new_timestamp=new_timestamp
        )
    else:
        return jsonify(error="Bad params"), 400
Пример #44
0
def get_all_reviews_by_place(place_id, review_id):
	try:
		review_query = Review.select().join(ReviewPlace).where(ReviewPlace.place == place_id, Review.id == review_id).get()
	except:
		return {'code': 10004, 'msg': 'Place does not exist'}, 400
	return review_query.to_dict()
Пример #45
0
def get_reviews(user_id):
	query = Review.select().join(ReviewUser).where(ReviewUser.user == user_id)
	return ListStyle.list(query,request)
Пример #46
0
def get_reviews_by_place(place_id):
	query = Review.select().join(ReviewPlace).where(ReviewPlace.place == place_id)
	return ListStyle.list(query,request)
Пример #47
0
def get_review(user_id, review_id):
	try:
		rev_query = Review.select().join(ReviewUser).where(ReviewUser.user_id == user_id, Review.id == review_id).get()
	except:
		return {"code": 404, "msg":"There are no reviews for this user"}, 404
	return rev_query.to_dict()