コード例 #1
0
ファイル: middletier.py プロジェクト: LiadBY/toilet_mapper
def add(request):
    error = ''
    response = ''
    status = 201
    if request.method == 'POST':
        data = request.POST.copy()        
        #We shouldn't be allowed to review a restroom twice
        if len(Review.objects.filter(user=request.user).filter(toilet=data['toilet'])) == 0:
            r = Review()
            toilet = Toilet.objects.get(pk=data['toilet'])
            data['date'] = currentTime()
            data['user'] = request.user
            data['toilet'] = toilet
            data['up_down_rank'] = 0;
            r.setattrs(data)
            r.save()
            toilet.updateRating(data['rank']) 
            response = serialize([r])
        else:
            error += 'Cannot write more than one review.\n'
            status = 403
    else:
        error += 'No POST data in request.\n'
        status = 415

    return HttpResponse(package_error(response,error), status=status)
コード例 #2
0
ファイル: views.py プロジェクト: wjzhwht/jeeves
def submit_review_view(request):
    import forms
    user = UserProfile.objects.get(username=request.user.username)

    try:
        if request.method == 'GET':
            paper_id = int(request.GET['id'])
        elif request.method == 'POST':
            paper_id = int(request.POST['id'])
        paper = Paper.objects.filter(id=paper_id).get()
        review = Review()
        review.paper = paper
        review.reviewer = user
        if request.method == 'POST':
            form = forms.SubmitReviewForm(request.POST, instance=review)
            if form.is_valid():
                form.save(paper)
                return HttpResponseRedirect("paper?id=%s" % paper_id)
        else:
            form = forms.SubmitReviewForm()
    except (ValueError, KeyError, Paper.DoesNotExist):
        paper = None
        form = None

    return render(request, "submit_review.html", {
        'form': form,
        'paper': paper,
        'which_page': "submit_review",
    })
コード例 #3
0
ファイル: main.py プロジェクト: jamesporter/2000reviews
    def post(self, serialised_key):
        if users.is_current_user_admin():
            #Either fetch review or create one
            review = None
            if serialised_key:
                review = db.get(db.Key(encoded=serialised_key))
            if not review:
                review = Review()
            #Add/update contents
            review.title = self.request.get('title')
            review.content = self.request.get('content')
            category = self.request.get('category')
            if category in Review.categories:
                review.category = category
            else:
                review.category = Review.categories[-1]  #i.e Other

            rating = self.request.get('rating')
            if rating in Review.ratings:
                review.rating = rating
            else:
                review.rating = Review.ratings[-1]   #i.e. N/A
            review.editDate = dt.datetime.now()
            review.put()
            self.redirect("/")
        else:
            self.redirect("/")
コード例 #4
0
def reviews_of_a_place(place_id):
    '''
        GET: list all reviews in a specific place
        POST: add a review to a specific place
    '''
    my_place = storage.get('Place', place_id)
    if my_place is None:
        abort(404)
    if request.method == 'POST':
        review_dict = request.get_json()
        if review_dict is None:
            return 'Not a JSON', 400
        if 'user_id' not in review_dict.keys():
            return 'Missing user_id', 400
        if 'text' not in review_dict.keys():
            return 'Missing text', 400
        if storage.get('User', review_dict['user_id']) is None:
            abort(404)
        review_dict['place_id'] = place_id
        my_review = Review(**review_dict)
        my_review.save()
        return jsonify(my_review.to_dict()), 201
    my_reviews = [review.to_dict() for review in storage.all('Review').values()
                  if review.place_id == place_id]
    return jsonify(my_reviews)
コード例 #5
0
    def test_review_likes(self):
        """Test liking a review"""
        r1 = Review(
            drink_id=self.d1id,
            rating=3.5,
            review="Test Review",
            user_id=self.uid,
            image=
            "https://images.unsplash.com/photo-1561150169-371f366b828a?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8YWxjb2hvbHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80"
        )

        r2 = Review(
            drink_id=self.d1id,
            rating=4.2,
            review="Another Test Review of same drink",
            user_id=self.uid,
            image="https://images.financialexpress.com/2018/03/beer-reuters.jpg"
        )
        u = User.signup("yetanothertest", "*****@*****.**", "password", None)
        uid = 888
        u.id = uid
        db.session.add_all([r1, r2, u])
        db.session.commit()

        u.likes.append(r1)

        db.session.commit()

        l = Likes.query.filter(Likes.user_id == uid).all()
        self.assertEqual(len(l), 1)
        self.assertEqual(l[0].reviews_id, r1.id)
        self.assertNotEqual(l[0].reviews_id, r2.id)
コード例 #6
0
ファイル: app.py プロジェクト: albagon/ny-diner-app
 def create_review_submission(id):
     error = False
     body = {}
     try:
         form = request.form
         review = Review(
             restaurant_id = id,
             name = form['name'],
             date = datetime.now(),
             rating = form['rating'],
             comments = form['comments']
         )
         review.insert()
         body['name'] = form['name']
     except:
         error = True
         db.session.rollback()
         print(sys.exc_info())
     finally:
         db.session.close()
     if not error:
         # on successful db insert, flash success
         flash('Thank you ' + body['name'] + ' for your review.', 'success')
     else:
         flash('An error occurred. Review could not be listed.', 'error')
     return redirect('/restaurants/'+str(id)+'/new_reviews')
コード例 #7
0
def post_review(place_id):
    """Creates a Review object
    Args:
        place_id: id of the place in uuid format
    Returns:
        jsonified version of created review object
    """
    if storage.get("Place", place_id) is None:
        abort(404)
    if not request.json:
        return jsonify({"error": "Not a JSON"}), 400
    review_dict = request.get_json()
    if "user_id" not in review_dict:
        return jsonify({"error": "Missing user_id"}), 400
    if storage.get("User", review_dict["user_id"]) is None:
        abort(404)
    if "text" not in review_dict:
        return jsonify({"error": "Missing text"}), 400
    else:
        r_user_id = review_dict["user_id"]
        r_text = review_dict["text"]
        review = Review(user_id=r_user_id, text=r_text, place_id=place_id)
        for key, value in review_dict.items():
            setattr(review, key, value)
        review.save()
        return jsonify(review.to_dict()), 201
コード例 #8
0
ファイル: views.py プロジェクト: labdalla/jeeves
def submit_review_view(request):
    try:
        if request.method == 'GET':
            paper_id = int(request.GET['id'])
        elif request.method == 'POST':
            paper_id = int(request.POST['id'])
        paper = Paper.objects.filter(id=paper_id).get()
        review = Review()
        review.paper = paper
        review.reviewer = request.user
        if request.method == 'POST':
            form = forms.SubmitReviewForm(request.POST, instance=review)
            if form.is_valid():
                form.save(paper)
                return HttpResponseRedirect("paper?id=%d" % paper_id)
        else:
            form = forms.SubmitReviewForm()
    except (ValueError, KeyError, Paper.DoesNotExist):
        paper = None
        form = None

    return render_to_response("submit_review.html", RequestContext(request, {
        'form' : form,
        'paper' : paper,
    }))
コード例 #9
0
    def post(self):
        loggedin_data = loggedin_parser.parse_args(data_parser("loggedin"))
        review_data = review_parser.parse_args(data_parser("review"))

        # Check if offer exists
        offer = session.query(Offer).filter(Offer.id == review_data["offer_id"]).first()
        if not offer:
            abort(400, message="Offer with id={} doesn't exist".format(review_data["offer_id"]))

        # Check if user is about to review himself
        if offer.user_id == loggedin_data["user_id"]:
            abort(400, message="Not allowed to review own offer")

        # Check if user has already reviewed this offer
        if session.query(Review).filter(Review.offer_id == offer.id,
                                        Review.author_id == loggedin_data["user_id"]).first():
            return [], 200

        # Create review
        review = Review(offer_id=offer.id,
                        author_id=loggedin_data["user_id"],
                        endorsed=review_data["endorsed"])

        if review_data["description"]:
            # Check if description exceeds max length
            if len(review_data["description"]) > 500:
                abort(400, message="Description exceeded max length of 500 chars")
            review.description = review_data["description"]

        session.add(review)
        session.flush()

        return review, 201
コード例 #10
0
def create_review(place_id):
    """
    Creates new review. If request body not valid JSON, raises 400
    If dict does not contain 'name' key, raise 400
    Returns review object with status 201
    """
    if not request.get_json():
        abort(400, "Not a JSON")

    kwargs = request.get_json()

    a = storage.get("Place", place_id)
    if a is None:
        abort(404)

    if not kwargs.get('user_id'):
        abort(400, "Missing user_id")
    if not kwargs.get('text'):
        abort(400, 'Missing text')

    a = storage.get("User", kwargs["user_id"])
    if a is None:
        abort(404)

    my_review = Review(place_id=place_id, **kwargs)
    storage.new(my_review)
    storage.save()

    return jsonify(my_review.to_dict()), 201
コード例 #11
0
def myreviews(request):
    reviews = Review.objects.filter(
        user=request.user).order_by('-date_started')
    context = {'reviews': reviews, 'alert_message': None}
    if request.method == "POST":
        new_title = request.POST.get('review', "")
        new_title = new_title.strip()
        if new_title != "":
            if not any(c in '!@#$%^&*\"\'' for c in new_title):
                if not reviews.filter(slug=slugify(new_title)).exists():
                    review = Review(user=request.user,
                                    title=new_title,
                                    date_started=datetime.datetime.now())
                    review.save()
                    reviews = Review.objects.filter(
                        user=request.user).order_by('-date_started')
                    context['reviews'] = reviews
                    context[
                        'alert_message'] = "A review was created with name: " + new_title
                else:
                    context[
                        'alert_message'] = "A review with this name already exists."
            else:
                context['alert_message'] = "Title cannot contain !@#$%^&*\"\'"
        elif request.POST.get('delete_review', "") != "":
            review_to_delete = reviews.get(
                slug=request.POST.get('delete_review'))
            if review_to_delete != None:
                review_to_delete.delete()
                context[
                    'alert_message'] = "Review deleted: " + review_to_delete.title
        else:
            context['alert_message'] = "You must give your new review a title."
    return render(request, 'ultimatereview/myreviews.html', context)
コード例 #12
0
ファイル: views.py プロジェクト: jeanqasaur/jeeves
def submit_review_view(request):
    import forms
    user = UserProfile.objects.get(username=request.user.username)

    try:
        if request.method == 'GET':
            paper_id = int(request.GET['id'])
        elif request.method == 'POST':
            paper_id = int(request.POST['id'])
        paper = Paper.objects.filter(id=paper_id).get()
        review = Review()
        review.paper = paper
        review.reviewer = user
        if request.method == 'POST':
            form = forms.SubmitReviewForm(request.POST, instance=review)
            if form.is_valid():
                form.save(paper)
                return HttpResponseRedirect("paper?id=%s" % paper_id)
        else:
            form = forms.SubmitReviewForm()
    except (ValueError, KeyError, Paper.DoesNotExist):
        paper = None
        form = None

    return render(request, "submit_review.html", {
        'form' : form,
        'paper' : paper,
        'which_page' : "submit_review",
    })
コード例 #13
0
def movie(movie_id):
    user = ctx.request.user
    movie = Movie.get(movie_id)
    movie = _get_movie_details(movie)
    if movie is None:
        raise notfound()
    movie.html_summary = markdown2.markdown(movie.summary)
    if user:
        history = History.find_first('where user_id=? and movie_id=?', user.id,
                                     movie_id)
        if not history:
            history = History(user_id=user.id, movie_id=movie_id)
            history.insert()
        else:
            history.created_at = time.time()
            history.update()
    reviews = Review.find_by(
        'where movie_id=? order by created_at desc limit 1000', movie_id)
    user_review = ''
    if user:
        user_review = Review.find_first('where user_id=? and movie_id=?',
                                        user.id, movie_id)
    return dict(movie=movie,
                reviews=reviews,
                user=user,
                user_review=user_review)
コード例 #14
0
ファイル: views.py プロジェクト: madrize/ecs
def post_review(request,
                template="reviews/post_review.html"):
    """
    View used to post a new review
    """
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        # get values
        s = request.GET.get('s','')
        t = request.POST['title']
        c = request.POST['content']
        r = request.POST['rating']
        # get product
        item = get_object_or_404(Product,slug=s)
        # new review
        rev = Review(title=t,content=c,product=item,sender=request.user,slug=slugify(t))
        rev.save()
        # add rating for the product
        item.votes = item.votes + 1
        item.total_rating = item.total_rating + int(r)
        item.save()
        # done!
        return HttpResponseRedirect("/")
    else:
        form = ReviewForm()
    
    return render_to_response ( template,
                                {'form':form},
                                context_instance=RequestContext(request))
コード例 #15
0
ファイル: core.py プロジェクト: Space-Cadets/Oberon
def post_review():
    # try:
    review_request = request.get_json()
    # print review_request
    review_record = Review(
        class_rating=review_request["classRating"],
        inst_rating=review_request["instRating"],
        review_body=review_request["reviewBody"],
        date_created=datetime.now(),
    )
    student_record = Student.query.filter_by(email=review_request["student"]).first()
    course_record = Course.query.filter_by(name=review_request["course"]).first()
    # section_record = Section.query.filter_by(crn=review_request['section']).first()
    instructor_record = Instructor.query.filter_by(name=review_request["instructor"]).first()
    traits = [Trait.query.get(trait_id) for trait_id in review_request["traits"]]
    review_record.traits = traits
    student_record.reviews.append(review_record)
    course_record.reviews.append(review_record)
    # section_record.reviews.append(review_record)
    instructor_record.reviews.append(review_record)
    # print review_record.traits
    db.session.add(review_record)
    db.session.add(student_record)
    # db.session.add(section_record)
    db.session.add(course_record)
    db.session.add(instructor_record)
    db.session.commit()
    return json_response({"status": "success", "message": "Review Successfully Added"}, 200)
コード例 #16
0
def create_review(place_id):
    """Creates a new review"""
    req = request.get_json()

    place = storage.get("Place", place_id)

    if place is None:
        abort(404)

    if req is None:
        return (jsonify("Not a JSON"), 400)

    try:
        req['user_id']
    except:
        return (jsonify("Missing user_id"), 400)

    try:
        req['text']
    except:
        return (jsonify("Missing text"), 400)

    req['place_id'] = place_id
    review_data = Review(**req)

    for key, value in req.items():
        setattr(review_data, key, value)

    review_data.save()
    return (jsonify(review_data.to_json()), 201)
コード例 #17
0
def get_place_rev(place_id):
    """
    Retrieves list of all Review objects and creates an instance as well
    """
    place = storage.get("Place", place_id)

    if place is None:
        abort(404)

    if request.method == 'GET':
        return jsonify([
            obj.to_dict() for obj in storage.all("Review").values()
            if obj.place_id == place_id
        ])

    if request.method == 'POST':
        if not request.json:
            abort(400, 'Not a JSON')
        if 'user_id' not in request.json:
            abort(400, 'Missing user_id')
        if 'text' not in request.json:
            abort(400, 'Missing text')
        data = request.get_json().get('text')
        user_id = request.get_json().get('user_id')
        user = storage.get('User', user_id)
        if user is None:
            abort(404)
        new_review = Review(user_id=user_id, text=data, place_id=place_id)
        new_review.save()
        return make_response(jsonify(new_review.to_dict()), 201)
コード例 #18
0
def create_review(place_id):
    '''
       Creates a new Review object and saves it to storage
    '''
    place = storage.get("Place", place_id)
    if not place:
        abort(404)

    if not request.json:
        abort(400)
        return jsonify({"error": "Not a JSON"})

    review_dict = request.get_json()
    if "user_id" not in review_dict:
        abort(400)
        return jsonify({"error": "Missing user_id"})
    elif "text" not in review_dict:
        abort(400)
        return jsonify({"error": "Missing text"})

    # Check that user_id is linked to actual User object
    user_check = storage.get("User", review_dict["user_id"])
    if not user_check:
        abort(404)

    review_text = review_dict["text"]
    user_id = review_dict["user_id"]
    review = Review(text=review_text, user_id=user_id, place_id=place_id)
    for k, v in review_dict.items():
        setattr(review, k, v)
    review.save()
    return jsonify(review.to_dict()), 201
コード例 #19
0
def post_review(request, template="reviews/post_review.html"):
    """
    View used to post a new review
    """
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        # get values
        s = request.GET.get('s', '')
        t = request.POST['title']
        c = request.POST['content']
        r = request.POST['rating']
        # get product
        item = get_object_or_404(Product, slug=s)
        # new review
        rev = Review(title=t,
                     content=c,
                     product=item,
                     sender=request.user,
                     slug=slugify(t))
        rev.save()
        # add rating for the product
        item.votes = item.votes + 1
        item.total_rating = item.total_rating + int(r)
        item.save()
        # done!
        return HttpResponseRedirect("/")
    else:
        form = ReviewForm()

    return render_to_response(template, {'form': form},
                              context_instance=RequestContext(request))
コード例 #20
0
def myreviews(request):
	reviews = Review.objects.filter(user=request.user).order_by('-date_started')
	context = {'reviews':reviews, 'alert_message':None}
	if request.method == "POST":
		new_title=request.POST.get('review', "")
		new_title = new_title.strip()
		if new_title!="":
			if not any(c in '!@#$%^&*\"\'' for c in new_title):
				if not reviews.filter(slug=slugify(new_title)).exists():
					review = Review(user=request.user, title=new_title, date_started=datetime.datetime.now())
					review.save()
					reviews = Review.objects.filter(user=request.user).order_by('-date_started')
					context['reviews']=reviews
					context['alert_message']="A review was created with name: "+new_title
				else:
					context['alert_message']="A review with this name already exists."
			else:
				context['alert_message']="Title cannot contain !@#$%^&*\"\'"
		elif request.POST.get('delete_review', "")!="":
			review_to_delete=reviews.get(slug=request.POST.get('delete_review'))
			if review_to_delete!=None:
				review_to_delete.delete()
				context['alert_message'] = "Review deleted: "+review_to_delete.title
		else:
			context['alert_message'] = "You must give your new review a title."
	return render(request, 'ultimatereview/myreviews.html', context)
コード例 #21
0
 def test_to_dict_result(self):
     """ Tests the result of the dict """
     review = Review()
     new_dict = review.to_dict()
     self.assertEqual(new_dict["__class__"], "Review")
     self.assertEqual(type(new_dict["created_at"]), str)
     self.assertEqual(type(new_dict["updated_at"]), str)
     self.assertEqual(type(new_dict["id"]), str)
コード例 #22
0
def _populate_book_reviews(book):
    reviews = _get_book_reviews_from_db(book.id)
    for review in reviews:
        temp_review = Review()
        temp_review.review, temp_review.rating, temp_review.user = review
        book.reviews.append(temp_review)
    book.gr_count, book.gr_rating = _get_gr_review(book.isbn)
    book.gr_rating = int(float(book.gr_rating))
コード例 #23
0
def review(business_id):
    response = jsonify({})
    review = Review(review_description=str(
        request.data.get('review_description', '')),
                    username=int(request.data.get('username', '')))
    response = jsonify(Review.get_review(review))
    response.status_code = 200
    return response
コード例 #24
0
ファイル: views.py プロジェクト: ypa/vzmmratings
def edit_hotel_review(hotel_id):
  if request.method == 'POST':
    hotel = Hotel.get_by_id(hotel_id)
    data = request.json
    review = Review(**data)
    review.hotel = hotel
    review.put()
    return hotel_reviews(hotel_id)
コード例 #25
0
ファイル: views.py プロジェクト: sampattuzzi/rent-review
def comment(request, property_id):
    property = Property.objects.get(id=property_id)
    text = request.POST['comment_body']
    title = request.POST['comment_title']
    if not title:
        title = text[:95] + '...'
    r = Review(body=text, title=title, author=request.user, subject=property)
    r.save()
    return HttpResponseRedirect(reverse('reviews:property', args=(property_id,)))
コード例 #26
0
def reviews(business_id):
    response = jsonify({})
    reviews = []
    reviews_list = Review.get_reviews()
    for review in reviews_list:
        if review.business_id == business_id:
            reviews.append(Review.get_review(review))
    response = jsonify(reviews)
    response.status_code = 200
    return response
コード例 #27
0
async def add_review_from_user( msg: types.Message , state: FSMContext ) :
	async with state.proxy() as data :
		book = Book.objects( id=data[ 'book_id' ] ).first()

		text = '{}\n{}'.format( msg.from_user.username or 'Аноним' , msg.text )
		new = Review( type=0 , text=text , book=book )
		new.save()
		book.reviews.append( new )
		book.save()
		await s( msg.from_user.id , 'Ваш отзыв принят!' )
コード例 #28
0
def add_review(request, wine_id):
    wine = get_object_or_404(Wine, pk=wine_id)
    form = ReviewForm(request.POST)
    if form.is_valid():
        rating = form.cleaned_data['rating']
        comment = form.cleaned_data['comment']
        user_name = request.user.username
        review = Review()
        review.wine = wine
        review.user_name = user_name
        review.rating = rating
        review.comment = comment
        review.pub_date = datetime.datetime.now()
        review.save()
        update_clusters()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(
            reverse('reviews:wine_detail', args=(wine.id, )))

    return render(request, 'reviews/wine_detail.html', {
        'wine': wine,
        'form': form
    })
コード例 #29
0
def add_review():
    body = request.get_json()

    new_review = Review(id_reader=body['id_reader'],
                        id_book=body["id_book"],
                        stars=body["stars"],
                        review=body["review"])

    Review.create(new_review)

    return jsonify({'message': 'Review created correctly'}), 200
コード例 #30
0
ファイル: main.py プロジェクト: jamesporter/2000reviews
 def get(self):
     index_text = memcache.get("index")
     if not index_text:
         count = Review.all(keys_only=True).count()
         last_twelve = Review.gql("ORDER BY creationDate DESC LIMIT 12")
         percentage = count/20.0
         if percentage > 100.0:
             percentage = 100
         template = jinja_environment.get_template("index.html")
         index_text = template.render({"categories":Review.categories, "percentage":percentage, "numReviews":count, "latestReviews":last_twelve})
         memcache.add("index", index_text)
     self.response.out.write(index_text)
コード例 #31
0
def review():
    content = request.form.get('review-content')
    article_id = request.form.get('article_id')
    review = Review(content=content)
    user = session.get('user_id')
    author = User.query.filter(User.id==user).first()
    article = Article.query.filter(Article.id==article_id).first()
    review.article=article
    review.author=author
    db.session.add(review)
    db.session.commit()
    return redirect(url_for('detail',article_id=article_id))
コード例 #32
0
ファイル: views.py プロジェクト: WyattHRichter/classNote
def submitAjax(request):
    if request.is_ajax() and request.GET:
        header = request.GET['header']
        text = request.GET['text']

        #the following are lazy checkers...
        #should implement something more foolproof
        #if time allows

        if "#" in header or "#" in text or \
            ">" in header or ">" in text or \
            "<" in header or "<" in text or \
            "%" in header or "%" in text or \
            "{" in header or "{" in text or \
            "}" in header or "}" in text:
            return HttpResponse('BAD_DATA')
        if len(header) == 0 or len(header) > 40 or \
            len(text) == 0 or len(text) > 1000:
            return HttpResponse('BAD_DATA')

        textArray = text.split(' ')

        #checks if the largest word is longer than 25 chars,
        #if so dont accept
        if (max(len(w) for w in textArray)) > 25:
            return HttpResponse('BAD_DATA')

        if 'http' in textArray or \
            '.com' in textArray or \
            '.org' in textArray:
            return HttpResponse('BAD_DATA')

        uniId = request.GET['uniId']
        college = request.GET['college']
        course = request.GET['course']
        rating = request.GET['rating']

        uni = University.objects.get(uniId=uniId)
        for col in uni.college_set.all():
            if(col.name==college):
                for cor in col.course_set.all():
                    if(cor.name==course):
                        review = Review(
                            header=header,
                            content=text,
                            course=cor,
                            rating=rating,
                        )
                        review.save()
                        return HttpResponse('SUCCESS')
        return HttpResponse('FAILURE')
    return index(request)
コード例 #33
0
def post_review():
    '''
        Create a review object
    '''
    if not request.json:
        return jsonify({"error": "Not a JSON"}), 400
    if 'user_id' not in request.json:
        return jsonify({"error": "Missing user_id"}), 400
    new_review = Review(user_id=request.get_json(["user_id"]))
    for key, value in request.get_json.items():
        setattr(new_review, key, value)
    new_review.save()
    return (jsonify(new_review.to_dict()), 201)
コード例 #34
0
ファイル: hello.py プロジェクト: hunterowens/svavapp
def add_review():
    if request.method == 'POST':
        data = request.data
        review = json.loads(data)
        review_new = Review(content=review['content'], rating=int(review['rating']))
        bath = session.query(Bathroom).filter(Bathroom.id == int(review['bathroom'])).first()
        review_new.bathroom = bath
        session.add(review_new)
        session.commit()
        return make_response(render_template('reviewAdded.html'), 200)
    else:
        baths = session.query(Bathroom).all()
        return render_template('addReviewForm.html', baths=baths)
コード例 #35
0
ファイル: views.py プロジェクト: RibRibble/python_march_2017
def create(request):
	print request.POST.__dict__
	book = Book.objects.get(id=request.POST['book_id'])
	user = User.objects.get(id=request.session['logged_in'])
	reviewData = {
		'content': request.POST['review'],
		'rating': request.POST['rating'],
		'book': book,
		'reviewer': user
	}
	newReview = Review(**reviewData)
	newReview.save()
	return redirect('books_show', id=book.id)
コード例 #36
0
ファイル: views.py プロジェクト: crumpledpaper/dhscanteen
  def post(self):
    # We set the same parent key on the 'review' to ensure each review is in
    # the same entity group. Queries across the single entity group will be
    # consistent. However, the write rate to a single entity group should
    # be limited to ~1/second.
    food_name = self.request.get('stall_name')
    review = Review(parent=stall_key(stall_name),
					content = self.request.get('content'))

    if users.get_current_user():
      author = users.get_current_user().nickname()
    
    review.put()
    self.redirect('/?' + urllib.urlencode({'stall_name': stall_name}))
コード例 #37
0
ファイル: views.py プロジェクト: dmattia/ND-Ratings
def add_review(request, profID):
	if request.method == 'POST':
		form = ReviewForm(request.POST)
		if form.is_valid():
			review = Review()
			review.professor = Professor.objects.get(id=profID)
			review.poster = request.user
			review.course = form.cleaned_data['course']	
			review.year_taken = form.cleaned_data['year_taken']	
			review.review = form.cleaned_data['review']	
			if Review.objects.filter(poster=request.user).filter(professor=review.professor).count > 0:
				params = {
					'message': 'You cannot review the same professor multiple times',
				}
				return render(request, 'message.html', params)
			review.save()
		return HttpResponseRedirect('/accounts/profs/profID/' + profID + '/')
	else:
		form = ReviewForm()
		prof = Professor.objects.get(id=profID)
		params = {
			'form': form,
			'formTitle': 'Add a review for ' + str(prof.firstName) + ' ' + str(prof.lastName),
		}
		return render(request, 'profSearch.html', params)
コード例 #38
0
def get_review_text(need_to_add=False):
    mes = pre_text_add_book if need_to_add else pre_text_review
    i = 0
    query = Review.objects(type=i).first()

    while query:
        mes += f'\n{query.text}'
        i += 1
        try:
            query = Review.objects(type=i).first()
        except:
            break
    # print(i,query)
    mes += '\nВыбери критерий для оценки'
    return mes
コード例 #39
0
def get_reviews_text():
    mes = pre_text_review
    i = 0
    query = Review.objects(type=i).first()

    while query:
        mes += f'\n{query.text}'
        i += 1
        try:
            query = Review.objects(type=i).first()
        except:
            break
    # print(i,query)
    mes += '\nВыбери критерий для оценки'
    return mes
コード例 #40
0
ファイル: getInsight.py プロジェクト: Crsytral/be
def getReviewInfo(inputFile):
    """
    review.csv
    data format:
    review ID | paper ID? | reviewer ID | reviewer name | unknown | text | scores | overall score | unknown | unknown | unknown | unknown | date | time | recommend?
    File has NO header

    score calculation principles:
    Weighted Average of the scores, using reviewer's confidence as the weights

    recommended principles:
    Yes: 1; No: 0; weighted average of the 1 and 0's, also using reviewer's confidence as the weights
    """
    review = Review(inputFile)
    return review.getReviewInfo()
コード例 #41
0
def approve_text():
    if 'text_id' not in request.form:
        return redirect('/', code=302)
    text_id = int(request.form.get('text_id'))

    try:
        text = Text.get(Text.id == text_id)
    except Exception:
        return redirect('/', code=302)

    if text.review.exists():
        return redirect('/', code=302)

    Review.create(text=text)
    return redirect('/', code=302)
コード例 #42
0
def create_reviews():
    '''
    Creates a Review.
    '''
    if not request.is_json:
        abort(400, "Not a JSON")
    update = request.get_json()
    if 'name' not in update.keys():
        abort(400, "Missing name")
    new_review = Review()
    storage.new(new_review)
    for key, value in update.items():
        new_review.__dict__[key] = value
    storage.save()
    return jsonify(new_review.to_dict()), 201
コード例 #43
0
 def list_any(self, editable, match):
     keyword = match[0]
     reviews = Review.get_by(
         session=self.database,
         title=keyword
     )
     return views.anyresults(reviews, keyword)
コード例 #44
0
    def getReview(self, request):
        """Get review for a session"""
        self._checkLoggedIn()

        reviews = Review.query(Review.session_name == request.session_name)

        return self._copyMutipleReivewsToReviewForm(query=reviews)
コード例 #45
0
ファイル: backup.py プロジェクト: GDGVienna/cfp-manager
 def get(self, confid, secret):
     """Download all speakers and proposals for a conference"""
     # Super-Reviewers
     committee = []
     if confid == 'droidcon-2016':
         committee = ['*****@*****.**',
                      '*****@*****.**']
     # get conference
     conference = Conference.get_by_id(confid)
     # check if the provided secret is correct
     if conference.secret != secret:
         self.response.http_status_message(403)
         return
     speakers = Speaker.query()
     proposals = Proposal.query(ancestor=conference.key)
     reviews = Review.query()
     speakers_dict = [dict(s.to_dict(), **dict(id=s.key.id()))
                      for s in speakers]
     proposals_dict = []
     # create a fast lookup table - reviews by parent
     reviews_by_parent = {}
     for r in reviews:
         parent = r.key.parent()
         rlist = reviews_by_parent[parent]
         if rlist is None:
             rlist = []
         rlist.append(r)
         reviews_by_parent[parent] = rlist
     # crete a fast lookup table - speaker by key
     speakers_by_id = {}
     for s in speakers:
         speakers_by_key[s.key] = s
     for p in proposals:
         p_dict = p.to_dict()
         p_dict['id'] = p.key.id()
         p_r = {}
         p_sum = 0
         for r in reviews_by_parent[p.key]:
             p_r[r.key.id()] = r.to_dict()
             if r.rating:
                 if r.key.id() in committee:
                     # double the rating!
                     p_sum = p_sum + r.rating
                 p_sum = p_sum + r.rating
         s = speakers_by_key[p.speaker]
         if s is not None:
             p_dict['speaker-email'] = s.email
             p_dict['speaker-name'] = s.name
             p_dict['speaker-surname'] = s.surname
             if s.rating:
                 p_sum = p_sum + s.rating
         p_dict['reviews'] = p_r
         p_dict['rating'] = p_sum
         proposals_dict.append(p_dict)
     self.response.headers['Content-Type'] = 'application/json'
     obj = {
         'speakers': speakers_dict,
         'proposals': proposals_dict,
     }
     self.response.out.write(json.dumps(obj, cls=DatastoreEncoder))
コード例 #46
0
def annotate(game):
    game.est = pytz.utc.localize(game.start).astimezone(est).time().strftime('%-I:%M %p')
    ratings = Review.objects(game = game)
    game.ratings = {
        'avg': int(round(ratings.average('rating'))) if ratings else None
    }
    return game
コード例 #47
0
ファイル: views.py プロジェクト: baa-archieve/esyakutuphanesi
def review():
    form = ReviewForm()
    conversation_id = request.form.get('conversation_id')

    if request.method == 'POST' and form.validate_on_submit():
        rating = request.form.get('rate')

        rq = Request.query. \
            filter(Request.id == form.request_id.data).first()

        # reviewed_user_id = rq.user_id if rq.user_id == current_user.id \
        #     else rq.from_user_id

        reviewed_user_id = rq.from_user_id

        new_review = Review(
            user_id=current_user.id,
            reviewed_user_id=reviewed_user_id,
            request_id=rq.id,
            comment=form.comment.data,
            rating=rating
        )

        db.session.add(new_review)
        db.session.commit()
        flash(u"Yorumunuz eklendi :)")
        return redirect('/show_stuff/%s' % rq.stuff_id)

    flash(u"Mesaj alanını boş bıraktınız.")
    return redirect('/conversation/%s' % conversation_id)
コード例 #48
0
    def test_delete_review(self):
        """Can a user delete their reviews?"""
        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.testuser.id
            review = Review(location='9191 S Polk Street Dallas', description='Tester', user_id=self.testuser.id)
            review.id = 1
            db.session.add(review)
            db.session.commit()

            resp = c.post(f'/delete/review/{review.id}', follow_redirects=True)

            html = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            self.assertIn('Welcome', html)
コード例 #49
0
 def test_child_review(self):
     """ Tests if the class User is a child class """
     review = Review()
     self.assertIsInstance(Review, BaseModel)
     self.assertTrue(hasattr(review, "id"))
     self.assertTrue(hasattr(review, "created_at"))
     self.assertTrue(hasattr(review, "updated_at"))
コード例 #50
0
ファイル: test_save.py プロジェクト: lmcdonough/fivesquare
def make_review():
	user = User.objects.get(username='******')
	establishment = Establishment.objects.get(name='Chrysler Building')

	review = Review()
	review.user = user
	review.establishment = establishment
	review.title = 'Site Seeing at the Chrysler Building.'
	review.text = 'We decided to go see the Chrysler Building and the view was pretty great. Price was also reasonable.'
	review.stars = 3
	review.tags = ['Site Seeing', 'Urban', 'Cheap']
	review.save()
	print "DONE"
コード例 #51
0
ファイル: controller.py プロジェクト: Neketek/revHand
 def addNewReview(self,title,text,rating):
     new = Review()
     new.title = title
     new.text = text
     new.rating = rating
     new.date = datetime.datetime.now().date()
     new.save()
コード例 #52
0
def add(request):
    error = ""
    response = ""
    status = 201
    if not request.user.is_authenticated():
        status = 403
        error += "Must be logged in to do that"
    elif request.method == "POST":
        data = request.POST.copy()
        # We shouldn't be allowed to review a restroom twice
        if len(Review.objects.filter(user=request.user).filter(toilet=data["toilet"])) == 0:
            r = Review()
            with transaction.commit_on_success():
                toilet = Toilet.objects.get(pk=data["toilet"])
                data["toilet"] = toilet
                toilet.updateRating(data["rank"])
            data["date"] = currentTime()
            data["user"] = request.user
            data["up_down_rank"] = 0
            r.setattrs(data)
            # validation
            r.full_clean()
            r.save()

            response = serialize([r])
        else:
            error += "Cannot write more than one review.\n"
            status = 403
    else:
        error += "No POST data in request.\n"
        status = 415

    return HttpResponse(package_error(response, error), status=status)
コード例 #53
0
ファイル: controller.py プロジェクト: Neketek/revHand
    def filterReviews(self,config=None,**kwargs):
        if(config is not None):
            kwargs = config
        if "id" in kwargs:
            return Review.get(Review.id == kwargs["id"])

        query = Review.select()
        if "title" in kwargs:
            query = query.where(Review.title.contains(kwargs["title"]))
        if "text" in kwargs:
            for item in kwargs["text"]:
                query = query.where(Review.text.contains(item))
        if "rating" in kwargs:
            if kwargs["rating"][0] == "less":
                query = query.where(Review.rating<kwargs["rating"][1])
            else:
                query = query.where(Review.rating>kwargs["rating"][1])

        return query
コード例 #54
0
ファイル: parse.py プロジェクト: kpx13/vv
def go():
    BASE_URL_AJEX = 'http://vspomnit-vse.com/ajax/otzyv'
    BASE_URL = 'http://vspomnit-vse.com/otzyivyi/'
    Review.objects.all().delete()
    for c, r in CATEG_AND_REVIEWS:
        cat = Category.objects.get(id=c)
        soup = BeautifulSoup(urllib2.urlopen(BASE_URL_AJEX + '&type=' + r).read())
        
        for a in soup.findAll('a', attrs={'class': 'otzyv'}):
            slug = a['href'][9:]
            name = a.findAll('h3')[0].string
            desc = u''.join([unicode(x) for x in a.contents[4:]]).strip()

            details_url = BASE_URL + slug
            details_soup = BeautifulSoup(urllib2.urlopen(details_url).read())
            
            content = details_soup.findAll('div', attrs={'id': 'left'})[0]
            content = ''.join([str(x) for x in content.contents[2:-1]]).replace('public/', 'static/public/')
            
            at_right = True
            if not desc:
                desc=content
                at_right = False
            
            slug = slug.replace(',', '').replace('.', '-')
            
            if Review.objects.filter(slug=slug).count() == 0:
                r = Review(name=name,
                       desc=desc,
                       content=content,
                       slug=slug,
                       at_right=at_right)
                r.save()
            else:
                r = Review.objects.get(slug=slug)
                print '!!! COPY !!!', r.id
            r.category.add(cat)
            r.save()
            
            print details_url
            
            
コード例 #55
0
ファイル: views.py プロジェクト: njdup/shesays
def create_review(request, company_id):
    """
    Creates a new review for the given company

    The incoming request must be a POST request
    TODO: Need to add some validations here
    """
    company = Company.objects.get(id=company_id)
    review_fields = {
        'content': request.POST['content'],
        'sentiment_label': request.POST['sentiment'],
        'company': company,
    }

    review_fields['sentiment_score'] = _get_sentiment_score(review_fields['sentiment_label'])
    new_review = Review(**review_fields)
    new_review.save()

    # TODO: Figure out better way to handle redirects
    return redirect('/companies/{}'.format(company_id))
コード例 #56
0
    def list_reviews(self, editable, match):
        author = editable.author.name.lower()
        self.fetcher.fetch_reviews(author)

        reviews = Review.get_by(
            session=self.database,
            author=author,
            limit=self.list_length
        )

        return views.reviewlist(editable.author, reviews)
コード例 #57
0
 def search_reviews(self, editable, match):
     author = editable.author.name.lower()
     self.fetcher.fetch_reviews(author)
     keywords = match[0] 
     reviews = Review.get_by(
         session=self.database,
         author=author,
         title=keywords,
         limit=self.list_length,
     )
     return views.searchresults(editable.author, reviews, keywords)
コード例 #58
0
ファイル: views.py プロジェクト: andres-root/webf
def review(request):
    saved = False
    review = ''
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            user_sender = User.objects.get(pk=request.POST['id_sender'])
            user_receiver = User.objects.get(pk=request.POST['id_receiver'])
            content = request.POST['content']
            sent = True
            re = Review()
            re.id_sender = user_sender
            re.id_receiver = user_receiver
            re.content = content
            re.save()
            mail_data = {}
            mail_data['subject'] = 'You have a new review.'
            mail_data['message'] = '''
                %s %s, <br> %s %s wrote a review about you. Here are the details<br>
                            <h3>Details: </h3><br>
                            %s
                                   ''' % (user_receiver.first_name, user_receiver.last_name, user_sender.first_name, user_sender.last_name, content)
            mail_data['from'] = '*****@*****.**'
            mail_data['sender'] = user_sender.email
            mail_data['receiver'] = user_receiver.email
            sent = utils.send_mail(mail_data)
            saved = True
            return HttpResponseRedirect('/trainer/%d' % (user_receiver.id))
        else:
            return HttpResponseRedirect('/')
コード例 #59
0
ファイル: main.py プロジェクト: jamesporter/2000reviews
 def get(self, category):
     template = jinja_environment.get_template("view.html")
     if users.is_current_user_admin():
         if category and category in Review.categories:
             reviews_collection = OrderedDict()
             for rating in Review.ratings:
                 reviews = Review.gql("WHERE rating = '%s' AND category = '%s'" % (rating, category))
                 if reviews.count() > 0:
                     reviews_collection[rating] = reviews
             self.response.out.write(template.render({"reviewsCollection": reviews_collection, "admin":True,"categories":Review.categories, "category":category}))
         else:
             reviews_collection = OrderedDict()
             for rating in Review.ratings:
                 reviews = Review.gql("WHERE rating = '%s'" % rating)
                 if reviews.count() > 0:
                     reviews_collection[rating] = reviews
             self.response.out.write(template.render({"reviewsCollection":reviews_collection, "admin":True,"categories":Review.categories}))
     #Not admin so cache etc
     else:
         if category and category in Review.categories:
             reviews_text = memcache.get("/view/%s" % category)
             if reviews_text is None:
                 reviews_collection = OrderedDict()
                 for rating in Review.ratings:
                     reviews = Review.gql("WHERE rating = '%s' AND category = '%s'" % (rating, category))
                     if reviews.count() > 0:
                         reviews_collection[rating] = reviews
                 reviews_text = template.render({"reviewsCollection":reviews_collection, "admin":False,"categories":Review.categories, "category":category})
                 memcache.add("/view/%s" % category, reviews_text)
         else:
             reviews_text = memcache.get("/view")
             if reviews_text is None:
                 reviews_collection = OrderedDict()
                 for rating in Review.ratings:
                     reviews = Review.gql("WHERE rating = '%s'" % rating)
                     if reviews.count() > 0:
                         reviews_collection[rating] = reviews
                 reviews_text = template.render({"reviewsCollection":reviews_collection, "admin":False,"categories":Review.categories})
                 memcache.add("/view", reviews_text)
         self.response.out.write(reviews_text)
コード例 #60
0
ファイル: review.py プロジェクト: GDGVienna/cfp-manager
 def post(self, confid):
     user = users.get_current_user()
     if not user:
         login_url = users.create_login_url(self.request.url)
         self.redirect(login_url)
         return
     # get the conference
     if confid.startswith('new:'):
         confid = confid[4:]
     conference = Conference.get_by_id(confid)
     # check if the user is an admin
     if user.email() not in conference.reviewers:
         self.response.out.write("You are not authorized")
         return
     # get proposal id & proposal
     proposal_id = long(self.request.get('proposal_id'))
     proposal = Proposal.get_by_id(id=proposal_id, parent=conference.key)
     if not proposal:
         self.response.out.write("No proposal found for this id (" +
                                 str(proposal_id) + ")")
         return
     # get existing review by this user
     review = Review.get_by_id(id=user.email(), parent=proposal.key)
     if not review:
         review = Review(id=user.email(), parent=proposal.key)
     # store value for the review
     review.comment = self.request.get('comment')
     if self.request.get('rating'):
         review.rating = int(self.request.get('rating'))
     # store in Data Store
     review.put()
     # redirect to get
     self.redirect(self.request.url)