예제 #1
0
class ReviewTest(unittest.TestCase):
    def setUp(self):
        self.user_James = User(id=1,
                               username='******',
                               password='******',
                               email='*****@*****.**',
                               bio="Time is an abstract")
        self.new_review = Review(id=5,
                                 review='Review for pitches',
                                 posted="2018-09-5",
                                 user=self.user_James)

    def tearDown(self):
        Review.query.delete()
        User.query.delete()

    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.id, 5)
        self.assertEquals(self.new_review.review, 'Review for pitches')
        self.assertEquals(self.new_review.posted, "2018-09-5")
        self.assertEquals(self.new_review.user, self.user_James)

    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.query.all()) > 0)

    def test_get_review_by_id(self):
        self.new_review.save_review()
        got_reviews = Review.get_reviews(12345)
        self.assertTrue(len(got_reviews) == 1)
예제 #2
0
 def setUp(self):
     """ 
 Set up method that will run before every Test.
 """
     self.new_review = Review(
         1, 'Python is awesome',
         'https://image.tmdb.org/t/p/w500/khsjha27hbs', 'A whole new World')
예제 #3
0
def write_review(request):
    context_dict = {}

    # Check if the request is of post type
    if request.method == 'POST':
        # Get the informationg from the form in required format
        donor_id = request.POST["donor"]
        hospital_id = request.POST["hospital"]
        data = {
            'donor': Donor.objects.get(pk=donor_id),
            'hospital': Hospital.objects.get(pk=hospital_id),
            'date': request.POST["time"],
            'review': request.POST["review_text"]
        }
        # Try to create a new review with given data
        try:
            review = Review()
            review.new_review(data)
            return JsonResponse({
                'success':
                True,
                'message':
                "The review has been succesfully published!"
            })
        except:
            return JsonResponse({
                'success':
                False,
                'message':
                "The provided login details are incorrect!"
            })

    else:
        return redirect("app:app")
예제 #4
0
def create_review():
    """
    Creates an review.
    """
    form = ReviewForm()
    print(request.get_json())
    # Get the csrf_token from the request cookie and put it into the
    # form manually to validate_on_submit can be used
    form['csrf_token'].data = request.cookies['csrf_token']
    print('<<<<<<<<<<<< csrf', form['csrf_token'].data)
    if form.validate_on_submit():
        print('validated form')
        app_id = form.data['application_id']
        first_rev = Review.query.filter(
            Review.application_id == app_id).first()
        review = Review(writer_id=form.data['writer_id'],
                        reviewee_id=form.data['reviewee_id'],
                        application_id=form.data['application_id'],
                        content=form.data['content'],
                        score=form.data['score'])
        db.session.add(review)
        db.session.commit()
        if first_rev:
            first_rev.response_id = review.id
            db.session.add(first_rev)
            db.session.commit()
        rev = review.to_dict()
        order_id = rev['order_id']
        order = Order.query.filter(Order.id == order_id).first()
        order.status = "Complete"
        db.session.add(order)
        db.session.commit()
        return review.to_dict()
    return 'invalid form'
예제 #5
0
    def process_reviews(self):
        logging.info('Parse reviews')
        with open(f'files/reviews.csv') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            line_count = 0
            for row in csv_reader:
                line_count += 1
                if line_count == 1:
                    continue

                product = Product.query.filter(Product.asin == row[0].strip()).first()
                if not product:
                    logging.error(f"There is no product with such asin code {row[0].strip()}")
                    continue

                review = Review()
                review.title = row[1]
                review.review = row[2]

                product.reviews.append(review)
                db.session.add(review)
                db.session.commit()

            logging.info(f'Processed {line_count} lines of reviews.')

        logging.info('End script')
예제 #6
0
 def setUp(self):
     '''
     Set up method that will run before every Test
     '''
     self.new_review = Review(1234, 'Python Must Be Crazy',
                              'A thrilling new Python Series',
                              '/khsjha27hbs', 8.5, 129993)
예제 #7
0
 def setUp(self):
     self.user_James = User(username = '******',password = '******', email = '*****@*****.**')
     self.new_review = Review(movie_id=12345,movie_title='Review for movies',image_path="https://image.tmdb.org/t/p/w500/jdjdjdjn",movie_review='This movie is the best thing since sliced bread',user = self.user_James )
     
     
     
     self.new_review = Review('movie_id','title','imageurl','review')
예제 #8
0
def seed_reviews():

    review1 = Review(
        writer_id=2,
        reviewee_id=1,
        application_id=7,
        response_id=3,
        content="Did a great job! Would recommend for any manual task!",
        score=5)
    review2 = Review(writer_id=2,
                     reviewee_id=1,
                     application_id=9,
                     content="Was energetic and helpful!",
                     score=4)
    review3 = Review(
        writer_id=1,
        reviewee_id=2,
        application_id=7,
        content="Was a top-notch volunteer experience! Great for all ages.",
        score=5)

    db.session.add(review1)
    db.session.add(review2)
    db.session.add(review3)

    db.session.commit()
예제 #9
0
class TestReview(unittest.TestCase):
    def setUp(self):
        self.user_James = User(username='******',
                               password='******',
                               email='*****@*****.**')
        self.new_review = Review(
            movie_id=12345,
            movie_title='Review for movies',
            image_path="https://image.tmdb.org/t/p/w500/jdjdjdjn",
            movie_review='This movie is the best thing since sliced bread',
            user=self.user_James)

    def tearDown(self):
        Review.query.delete()
        User.query.delete()

    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.movie_id, 12345)
        self.assertEquals(self.new_review.movie_title, 'Review for movies')
        self.assertEquals(self.new_review.image_path,
                          "https://image.tmdb.org/t/p/w500/jdjdjdjn")
        self.assertEquals(self.new_review.movie_review,
                          'This movie is the best thing since sliced bread')
        self.assertEquals(self.new_review.user, self.user_James)

    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.query.all()) > 0)

    def test_get_review_by_id(self):
        self.new_review.save_review()
        got_reviews = Review.get_reviews(12345)
        self.assertTrue(len(got_reviews) == 1)
예제 #10
0
class TestReview(unittest.TestCase):

    def setUp(self):
        self.user_Anita = User(username = '******',password = '******', email = '*****@*****.**')
        self.new_review = Review(movie_id=12345,movie_title='Review for movies',
        image_path="https://image.tmdb.org/t/p/w500/wwemzKWzjKYJFfCeiB57q3r4Bcm.png",movie_review='This movie is the best thing since sliced bread'
        ,user = self.user_Anita )


    def tearDown(self):
        Review.query.delete()
        User.query.delete()

    def test_instance(self):
        self.assertTrue(isinstance(self.new_review,Review))


    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.movie_id,12345)
        self.assertEquals(self.new_review.movie_title,'Review for movies')
        self.assertEquals(self.new_review.image_path,"https://image.tmdb.org/t/p/w500/wwemzKWzjKYJFfCeiB57q3r4Bcm.png")
        self.assertEquals(self.new_review.movie_review,'This movie is the best thing since sliced bread')
        self.assertEquals(self.new_review.user,self.user_Anita)


    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.query.all())>0)


    def test_get_review_by_id(self):

        self.new_review.save_review()
        got_reviews = Review.get_reviews(12345)
        self.assertTrue(len(got_reviews) == 1)
예제 #11
0
class TestReview(unittest.TestCase):

    def setUp(self):
        self.new_review = Review(12345,'Review for movies',"https://image.tmdb.org/t/p/w500/jdjdjdjn",'This movie is the best thing since sliced bread')


    def tearDown(self):
        Review.clear_reviews()

    def test_instance(self):
        self.assertTrue(isinstance(self.new_review,Review))


    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.movie_id,12345)
        self.assertEquals(self.new_review.title,'Review for movies')
        self.assertEquals(self.new_review.imageurl,"https://image.tmdb.org/t/p/w500/jdjdjdjn")
        self.assertEquals(self.new_review.review,'This movie is the best thing since sliced bread')


    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.all_reviews)>0)

    def test_get_review_by_id(self):
        self.new_review.save_review()
        got_reviews = Review.get_reviews(12345)
        self.assertTrue(len(got_reviews)==1)
예제 #12
0
def home():
    forms = DateForm()
    if request.method == 'POST':
        id = request.form['id']
        Review.accept_review(id)
        return redirect(url_for("app.home"))
    proposed_reviews = Review.query.order_by(
        Review.id).filter(Review.status == 2).filter(
            or_(Review.requestor == current_user.id,
                Review.reviewer == current_user.id)).filter(
                    Review.last_changed == current_user.id)
    received_reviews = Review.query.order_by(
        Review.id).filter(Review.status == 2).filter(
            or_(Review.requestor == current_user.id,
                Review.reviewer == current_user.id)).filter(
                    Review.last_changed != current_user.id)
    progress_reviews = Review.query.order_by(
        Review.id).filter(Review.status == 3).filter(
            or_(Review.requestor == current_user.id,
                Review.reviewer == current_user.id))
    completed_reviews = Review.query.order_by(
        Review.id).filter(Review.status == 4).filter(
            or_(Review.requestor == current_user.id,
                Review.reviewer == current_user.id)).order_by(
                    Review.date).limit(4)
    if forms.validate_on_submit:
        print('8888888888888888888888888888888888888888888888888')

    return render_template('home.html',
                           user=current_user,
                           forms=forms,
                           proposed_reviews=proposed_reviews,
                           received_reviews=received_reviews,
                           progress_reviews=progress_reviews,
                           completed_reviews=completed_reviews)
예제 #13
0
def review_add(asin=None):
    if request.method == 'PUT':

        product = Product.query.filter(Product.asin == asin).first()
        if not product:
            return jsonify(status='error', errors=[{'message': ['No such product asin found']}])

        try:
            title = request.json.get('title')
            review = request.json.get('review')
        except AttributeError:
            return jsonify(status='error', errors=[{'validation': ['Check out your JSON and headers']}])

        if not title or not review:
            return jsonify(status='error', errors=[{'validation': ['Fill title & review fields']}])

        new_review = Review()
        new_review.title = title
        new_review.review = review

        product.reviews.append(new_review)
        db.session.add(new_review)
        db.session.commit()

        # TODO :)
        cache.clear()

        return jsonify(status='success')

    return jsonify(status='error', errors=[{'message': 'Wrong request format'}])
예제 #14
0
 def add_review(id):
     businesses = Business.check_business_exists(id)
     all_business = []
     for business in businesses:
         obj = {
             "name": business.name
         }
         all_business.append(obj)
     if not all_business:
         message = "cannot add review business that does not exist"
         response = jsonify({"message": message, "status_code": 404})
         # 404 if business does not exist
         response.status_code = 404
         return response
     opinion = str(request.data.get('opinion', ''))
     rating = int(request.data.get('rating', ''))
     if rating and opinion:
         new_review = Review(opinion=opinion, rating=rating, business_main=id)
         new_review.save()
         message = "succesfully added the review"
         response = jsonify({"message": message})
         response.status_code = 201
         return response
     message = "make sure the opinion and rating are included"
     response = jsonify({"message": message, "status_code": 400})
     response.status_code = 400
     return response  
예제 #15
0
class TestReview(unittest.TestCase):

    def setup(self):
        '''
        Set up method that will run before every Test
        '''
        self.user_Ryan = User(username = '******',password = '******', email = '*****@*****.**')
        self.new_review = Review(movie_id = 12345,movie_title = 'Review for movies',image_path = "https://image.tmdb.org/t/p/w500/jdjdjdjn",movie_review = 'This movie is the best thing since sliced bread',user = self.user_Ryan)

    def test_instance(self):
        self.assertTrue(isinstance(self.new_review,Review))

    def tearDown(self):
        Review.query.delete()
        User.query.delete()

    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.movie_id,12345)
        self.assertEquals(self.new_review.movie_title,'Review for movies')
        self.assertEquals(self.new_review.image_path,"https://image.tmdb.org/t/p/w500/jdjdjdjn")
        self.assertEquals(self.new_review.movie_review,'This movie is the bestthing since sliced bread')
        self.assertEquals(self.new_review.user,self.user_Ryan)

    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.query.all())>0)

    def test_get_review_by_id(self):
        self.new_review.save_review()
        got_reviews = Review.get_reviews(12345)
        self.assertTrue(len(got_reviews) == 1)
예제 #16
0
class ReviewModelTest(unittest.TestCase):
    def setUp(self):
        self.user_James = User(username='******',
                               password='******',
                               email='*****@*****.**')
        self.new_review = Review(
            pitch_id=12345,
            pitch_title='Review for pitches',
            review='This pitch is the best thing since sliced bread',
            user=self.user_James)

    def tearDown(self):
        Review.query.delete()
        User.query.delete()

    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.pitch_id, 12345)
        self.assertEquals(self.new_review.pitch_title, 'Review for pitches')
        self.assertEquals(self.new_review.movie_review,
                          'This pitch is the best thing since sliced bread')
        self.assertEquals(self.new_review.user, self.user_James)

    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.query.all()) > 0)

    def test_get_review_by_id(self):

        self.new_review.save_review()
        got_reviews = Review.get_reviews(12345)
        self.assertTrue(len(got_reviews) == 1)
예제 #17
0
class TestReview(unittest.TestCase):
    def setUp(self):
        self.new_review = Review(
            '1235', 'Review for movies',
            'https://image.tmd.org/t/p/w500/hjejhggsf'
            'This the best movie so far')

    def tearDown(self):
        Review.clear_views()

    def test_instance(self):
        self.assertTrue(isinstance(self.new_review, Review))

    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.movie_id, 1235)
        self.assertEquals(self.new_review.title, 'Review for movies')
        self.assertEquals(self.new_review.imageurl,
                          'https://image.tmdeb.org/n/g/w500/webhbcc')

    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.all_reviews) > 0)

    def test_get_review_by_id(self):

        self.new_review.save_review()
        got_reviews = Review.get_reviews(1235)
        self.assertTrue(len(got_reviews) == 1)
예제 #18
0
def addReview():
    """
    Posts a New Review
    """
    form = ReviewForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    print('Request', request.json)
    print('Form', form.data)
    if form.validate_on_submit():
        print('Current User', current_user)
        review = Review(user_id=(form.data['user']),
                        restaurant_id=(form.data['restaurant']),
                        body=form.data['body'],
                        rating=(form.data['rating']),
                        bags=form.data['bags'],
                        utensils=form.data['utensils'],
                        napkins=form.data['napkins'],
                        cups=form.data['cups'],
                        bowls=form.data['bowls'],
                        straws=form.data['straws'],
                        created=datetime.datetime.now(),
                        updated=datetime.datetime.now())
        print('Review', review)
        db.session.add(review)
        db.session.commit()
        return review.to_dict()
    return {'errors': validation_errors_to_error_messages(form.errors)}
예제 #19
0
class TestReview(unittest.TestCase):

    def setUp(self):
        self.user_James = User(username = '******',password = '******', email = '*****@*****.**')
        self.new_review = Review(movie_id=12345,movie_title='Review for movies',image_path="https://image.tmdb.org/t/p/w500/jdjdjdjn",movie_review='This movie is the best thing since sliced bread',user = self.user_James )


    def tearDown(self):
        Review.query.delete()
        User.query.delete()

    def test_instance(self):
        self.assertTrue(isinstance(self.new_review,Review))


    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.movie_id,12345)
        self.assertEquals(self.new_review.movie_title,'Review for movies')
        self.assertEquals(self.new_review.image_path,"https://image.tmdb.org/t/p/w500/jdjdjdjn")
        self.assertEquals(self.new_review.movie_review,'This movie is the best thing since sliced bread')
        self.assertEquals(self.new_review.user,self.user_James)


    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.query.all())>0)


    def test_get_review_by_id(self):

        self.new_review.save_review()
        got_reviews = Review.get_reviews(12345)
        self.assertTrue(len(got_reviews) == 1)
예제 #20
0
class TestReview(unittest.TestCase):
    def setUp(self):
        self.new_review = Review(12345, "Review for movies",
                                 "https://image.tmdb.org/t/p/w500/jdjdjdjn",
                                 "good")

    def tearDown(self):
        '''
        tearDown method that does clean up after each test case has run.
        '''
        Review.all_reviews = []

    def test_instance(self):
        self.assertTrue(isinstance(self.new_review, Review))

    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.movie_id, 12345)
        self.assertEquals(self.new_review.title, 'Review for movies')
        self.assertEquals(self.new_review.imageurl,
                          "https://image.tmdb.org/t/p/w500/jdjdjdjn")
        self.assertEquals(self.new_review.review, 'good')

    def test_save_review(self):
        '''
        test_save_review test case to test if the review object is saved into
         the review list
        '''
        self.new_review.save_review()  # saving the new review
        self.assertEqual(len(Review.all_reviews), 1)
예제 #21
0
    def save_item(self, scraped_text_dto):
        """Saves an item to a database. If something goes wrong, rolls back
        the transaction and runs self.fail().

        Arguments:
            scraped_text_dto: An instance of ScrapedTextDTO
        """
        self.retrieved_count += 1
        property = Property.objects.get(pk=scraped_text_dto.property_id)
        content = scraped_text_dto.content
        content = content.replace("<br>", "\n");
        pub_date = datetime.datetime.strptime(scraped_text_dto.pub_date, scraped_text_dto.date_format)
        rating = float(scraped_text_dto.rating)
        if len(Review.objects.filter(text=content, grade=rating)):
            print "Already existed"
        else:
            try:
                id_gen = Review.objects.latest("id").id
            except Review.DoesNotExist:
                id_gen = -1
            rated_scraped_text = Review(text=content, created_date=pub_date, grade=rating, id=id_gen+1)
            rated_scraped_text.save()
            # Save it to this list in order to send out an alert
            property.reviews.add(rated_scraped_text)
            if self.verbose:
                print "Saved to DB: {0}".format(rated_scraped_text)
예제 #22
0
def review():
    if request.method == 'GET':
        if len(request.args) != 0:
            form = ReviewForm(request.args)
        else:
            flash("Invalid request. Please search for provider first and then"
                  " add review.")
            return redirect(url_for('main.index'))
    elif request.method == 'POST':
        form = ReviewForm()
    provider = Provider.query.get(form.id.data)
    form.category.choices = [(c.id, c.name) for c in provider.categories]
    if form.validate_on_submit():
        pictures = Picture.savePictures(form)
        Review.create(user_id=current_user.id,
                      provider_id=form.id.data,
                      category_id=form.category.data,
                      rating=form.rating.data,
                      cost=form.cost.data,
                      price_paid=form.price_paid.data,
                      description=form.description.data,
                      service_date=form.service_date.data,
                      comments=form.comments.data,
                      pictures=pictures)
        flash("review added")
        return redirect(url_for('main.index'))
    elif request.method == "POST" and not form.validate():
        return render_template("review.html", title="Review", form=form), 422
    if not current_user.email_verified:
        disableForm(form)
        flash("Form disabled. Please verify email to unlock.")
    return render_template("review.html", title="Review", form=form)
예제 #23
0
class TestReview(unittest.TestCase):
    def setUp(self):
        self.new_user = User(user_id=3000,
                             user_name='Sandy',
                             user_email='sandys@gmail',
                             user_password='******')
        self.new_review = Review(review_id=12300,
                                 comment='Yes Yes',
                                 user=self.new_user)

    def tearDown(self):
        Review.query.delete()
        User.query.delete()

    def test_instance(self):
        self.assertTrue(isinstance(self.new_review, Review))

    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.review_id, 12300)
        self.assertEquals(self.new_review.comment, 'Yes Yes')
        self.assertEquals(self.new_review.user, self.new_user)

    def test_review_saving(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.query.all()) > 0)
예제 #24
0
def requestor():
    cform = CreateForm()
    if cform.validate_on_submit():
        print(current_user.first_name)
        review = Review(title=cform.title.data,
                        description=cform.description.data,
                        biling=cform.biling.data,
                        status=1,
                        requestor=current_user.id,
                        requestor_name=User.get_name(current_user.id),
                        date=datetime.datetime.now(),
                        pic=current_user.profile_pic)
        db.session.add(review)
        db.session.commit()
        tags = cform.tags.data
        print(tags)
        tag_list = tags.split(',')
        print('4444444444444444')
        print(tag_list)
        Review.setTags(tag_list, review.id)
        print('333333333333333333')
        return redirect(url_for("app.requestor"))
    else:
        print('bad')

    return render_template('requestor.html', cform=cform, user=current_user)
예제 #25
0
class TestReview(unittest.TestCase):
    def setUp(self):
        self.new_review = Review(
            movie_id=4598,
            review_title="Python master",
            imageurl="https://image.tmdb.org/t/p/w500/mastery",
            review="I got this bruv! I got this")

    def tearDown(self):
        Review.clear_reviews()

    def test_instance(self):
        self.assertTrue(isinstance(self.new_review, Review))

    def test_check_instance_variables(self):
        self.assertEquals(self.new_review.movie_id, 12345)
        self.assertEquals(self.new_review.title, 'Review for movies')
        self.assertEquals(self.new_review.imageurl,
                          "https://image.tmdb.org/t/p/w500/jdjdjdjn")
        self.assertEquals(self.new_review.review,
                          'This movie is the best thing since sliced bread')

    def test_save_review(self):
        self.new_review.save_review()
        self.assertTrue(len(Review.all_reviews) > 0)
예제 #26
0
    def test_clear_review(self):
        self.new_review.save_review ()
        test_review=Review(1234,'Python Must Be Crazy','A thrilling new Python Series','/khsjha27hbs',8.5,129993)
 
        test_review.save_review()

        self.new_review.clear_review ()
        self.assertTrue(len(Review.all_reviews), 1)
예제 #27
0
 def setUp(self):
     self.new_user = User(user_id=3000,
                          user_name='Sandy',
                          user_email='sandys@gmail',
                          user_password='******')
     self.new_review = Review(review_id=12300,
                              comment='Yes Yes',
                              user=self.new_user)
예제 #28
0
파일: seed.py 프로젝트: mgraczyk/exomind
    def handle(self, *args, **options):
        reviews = csv_to_json(
            os.path.join(os.path.dirname(__file__),
                         '../../../test/data/reviews.csv'))

        user, _ = User.objects.get_or_create(email='*****@*****.**',
                                             defaults={'username': '******'})
        for review in reviews:
            Review.create_or_update(user, review, None)
예제 #29
0
 def setUp(self):
     self.user_James = User(username='******',
                            password='******',
                            email='*****@*****.**')
     self.new_review = Review(
         pitch_id=12345,
         pitch_title='Review for pitches',
         review='This pitch is the best thing since sliced bread',
         user=self.user_James)
예제 #30
0
def make_businessreview(business_id):
    current_user = get_jwt_identity()
    business_to_review = Business.query.filter_by(id=business_id).first()
    print(business_to_review)
    if request.method == 'POST':
        if not business_to_review:
            return jsonify(
                {'message': 'You can only review an existing business'}), 409
        try:
            required_fields = ['value', 'comments']
            data = check_blank_key(request.get_json(), required_fields)
        except AssertionError as err:
            msg = err.args[0]
            return jsonify({"message": msg}), 422
        value = validate_buss_data_null(data['value'])
        comments = validate_buss_data_null(data['comments'])
        if not value or not comments:
            return jsonify(
                {'message':
                 'You have to enter a review value and comment'}), 400
        if current_user == business_to_review.user_id:
            return jsonify({'message':
                            'You can not review your own business'}), 403
        new_review = Review(value=value,
                            comments=comments,
                            business_id=business_id,
                            user_id=current_user)
        new_review.save()
        display_review = Review.query.filter_by(id=new_review.id).first()
        info = display_review.accesible()

        return jsonify({
            'message': 'You have successfully created a review',
            'Review': info
        }), 201

    # retreving a single business's reviews
    if not business_to_review:
        return jsonify({'message': 'Enter an existing business'}), 409
    all_reviews = Review.get_all(Review)

    # using lambda and map
    def func(review):
        return review.accesible(
        ) if review.business_id == business_id else False

    all_reviews = filter(lambda item: item and True, map(func, all_reviews))
    data = list(all_reviews)
    if len(data) == 0:
        return jsonify({'message': 'No review for this business'}), 201

    return jsonify({
        'message':
        'Reviews for business with id {} are :'.format(business_id),
        'reviews ':
        data
    }), 201
예제 #31
0
def add(tasting_id):
    form = ReviewForm(tasting_id=tasting_id)
    current_time = datetime.utcnow()
    if form.validate_on_submit():
        filename = secure_filename(form.image.data.filename)
        # set age to 0 if it has not been entered
        if form.age.data == "":
            age = 0
        else:
            age = int(form.age.data)
        if form.brand_id.data is '0':
            brand = Brand(name=form.brand_name.data)
            db.session.add(brand)
            db.session.flush()
            review = Review(order=form.order.data,
                            notes=form.notes.data,
                            tasting_note=form.tasting_note.data,
                            img_name=filename,
                            name=form.name.data,
                            age=age,
                            max_rating=form.max_rating.data,
                            avg_rating=form.avg_rating.data,
                            min_rating=form.min_rating.data,
                            author=current_user,
                            brand_id=brand.id,
                            tasting_id=form.tasting_id.data)
        else:
            review = Review(order=form.order.data,
                            notes=form.notes.data,
                            tasting_note=form.tasting_note.data,
                            img_name=filename,
                            name=form.name.data,
                            age=form.age.data,
                            max_rating=form.max_rating.data,
                            avg_rating=form.avg_rating.data,
                            min_rating=form.min_rating.data,
                            author=current_user,
                            brand_id=form.brand_id.data,
                            tasting_id=form.tasting_id.data)
        db.session.add(review)
        db.session.commit()

        pathlib.Path(current_app.config['UPLOAD_FOLDER'] + '/' +
                     str(review.id)).mkdir(parents=True, exist_ok=True)
        form.image.data.save(current_app.config['UPLOAD_FOLDER'] + '/' +
                             str(review.id) + '/' + filename)
        rotateImage(
            current_app.config['UPLOAD_FOLDER'] + '/' + str(review.id) + '/',
            filename)
        flash('Your review is now live!')
        return redirect(
            url_for('main.tasting', tasting_id=form.tasting_id.data))
    return render_template(
        'add_review.html',
        title='Add Review',
        form=form,
    )
예제 #32
0
    def test_get_reviews(self):
        self.new_review.save_review()
        test_review=Review(1234,'Python Must Be Crazy','A thrilling new Python Series','/khsjha27hbs',8.5,129993)
 
        test_review.save_review()

        found_review = Review.get_reviews("1234")

        self.assertEqual(found_review.title, test_review.title)
예제 #33
0
def create_review():
    """ Post a new review to the database. Return the review object.

    |  **URL:** /beer/api/v0.1/reviews
    |  **Method:** POST
    |  **Query Args:** None
    |  **Authentication:** Token/Password
    |  **Expected Data:** beer_id, aroma, appearance, taste, palate, bottle_style

    Example:

    *Review beer with id# 4 with scores, 3, 3, 8, 4, 1* ::

      POST http://domain.tld/beer/api/v0.1/reviews
      data={"beer_id":4, "aroma":3, "appearance":3, "taste":8, "palate":4, "bottle_style":1}

    *Review beer with id# 2 with scores, 1, 1, 5, 5, 5* ::

      POST http://domain.tld/beer/api/v0.1/reviews
      data={"aroma":"1", "appearance":"1", "taste":"5", "palate":"5", "bottle_style":"5", "beer_id":"http://domain.tld/beer/api/v0.1/beers/2"}

    """

    score = dict()
    score['aroma'] = request.json.get(u'aroma')
    score['appearance'] = request.json.get(u'appearance')
    score['taste'] = request.json.get(u'taste')
    score['palate'] = request.json.get(u'palate')
    score['bottle_style'] = request.json.get(u'bottle_style')
    score['beer_id'] = request.json.get(u'beer_id')

    for key, value in score.items():
        if value == None:
            flash(u'Missing value for '+key, 'error')
            abort(400)
        if key == 'beer_id':
            bid = Beer.id_or_uri_check(str(value))
            if bid is None:
                flash(u'That beer does not exist, please create it first', 'error')
                abort(400)
            # Has user reviewed that beer this week?
            for review in g.user.reviews:
                if review.beer_id == bid:
                    if (datetime.utcnow() - review.created_on) < timedelta(weeks=1):
                        flash(u'You have already reviewed that beer this week!', 'error')
                        abort(400)
    if not Review.validate_score_values(score):
        flash(u'Invalid score data, please try again', 'error')
        abort(400)
    review = Review(bid, g.user.id, score)
    db.session.add(review)
    db.session.commit()
    return(jsonify({'results': review.serialize(), \
            'status': 'Review created successfully'}), 201, \
            {'Location': url_for('get_review', id=review.id, _external=True)})
예제 #34
0
파일: views.py 프로젝트: EnterAll/Diloo
def ur(request):
    context = RequestContext(request)
    review = Review()
    review.content = request.POST['content']
    review.title = request.POST['title']
    review.category = Category.objects.get(id=request.POST['category'])
    review.readings = 0
    review.critic = Critic.objects.get(user=request.user)
    review.save()

    return HttpResponse(review.id)
예제 #35
0
    def test_get_review_by_id(self):

        self.new_review.save_review()
        got_reviews = Review.get_reviews(12345)
        self.assertTrue(len(got_reviews) == 1)
예제 #36
0
파일: views.py 프로젝트: mocangli/learngit
def api_checkForm(request):
    user = get_auth(request)
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))

        review = Review()
        review.proofread_user = data['proofread']
        review.review_user = data['review']
        review.countersign_user = data['countersign']
        review.approved_user = data['approved']
        review.Issued_user = data['Issued']
        review.dispose_user = data['proofread']
        review.file_id = data['file_id']
        review.user_name = user.name
        review.save()
        file=Myfile.objects.get(pk=review.file_id)
        file.dispose_user = review.dispose_user
        file.save()
        return JsonResponse({'review':review.toDict()})
예제 #37
0
 def setUp(self):
     self.user_James = User(username = '******',password = '******', email = '*****@*****.**')
     self.new_review = Review(movie_id=12345,movie_title='Review for movies',image_path="https://image.tmdb.org/t/p/w500/jdjdjdjn",movie_review='This movie is the best thing since sliced bread',user = self.user_James )
예제 #38
0
def new_review(course_id):
    course = Course.query.get(course_id)
    if not course:
        abort(404)
    user = current_user
    review = Review.query.filter_by(course=course, author=user).first()
    if not review:
        review = Review()
        review.course = course
        review.author = user
        is_new = True
    else:
        is_new = False

    message = ''
    form = ReviewForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            # check validity of term
            if str(form.term.data) not in course.term_ids:
                abort(404)

            if form.is_mobile.data:
                form.content.data = markdown.markdown(form.content.data)
            form.content.data, mentioned_users = editor_parse_at(form.content.data)
            form.content.data = sanitize(form.content.data)
            form.populate_obj(review)

            if is_new:
                review.add()
                for user in set(current_user.followers + course.followers + course.joined_users):
                    user.notify('review', review, ref_display_class='Course')
                # users can only receive @ notifications for new reviews
                for user in mentioned_users:
                    user.notify('mention', review)
            else:
                review.save()
            return redirect(url_for('course.view_course',course_id=course_id))
        else: # invalid submission, try again
            if form.content.data:
                review.content = sanitize(form.content.data)
            if form.difficulty.data:
                review.difficulty = form.difficulty.data
            if form.homework.data:
                review.homework = form.homework.data
            if form.gain.data:
                review.gain = form.gain.data
            if form.rate.data:
                review.rate = form.rate.data
            message = '提交失败,请编辑后重新提交!'

    polls = [
        {'name': 'difficulty', 'display': '课程难度', 'options': ['简单', '中等', '困难'] },
        {'name': 'homework', 'display': '作业多少', 'options': ['不多', '中等', '超多'] },
        {'name': 'grading', 'display': '给分好坏', 'options': ['超好', '厚道', '杀手'] },
        {'name': 'gain', 'display': '收获多少', 'options': ['很多', '一般', '没有'] },
    ]
    return render_template('new-review.html', form=form, course=course, review=review, polls=polls, message=message, is_new=is_new)