def rate_movie(): """Rate a movie.""" score = request.form.get("rating") movie_id = request.form.get("movie_id") user_id = session.get("user_id") timestamp = datetime.datetime.now() if "user_id" not in session: flash("Hey, you're not logged in!") return redirect("/login") rating = Rating.query.filter_by(movie_id=movie_id, user_id=user_id).first() if not rating: # Only add a rating if the user is logged in rating = Rating(movie_id=movie_id, user_id=user_id, score=score, timestamp=timestamp) else: rating.score = score db.session.add(rating) db.session.commit() flash("Successfully rated movie.") return redirect("/movies/{}".format(movie_id))
def add_rating(): """Adding Skirun rating.""" skirun_id = request.form.get('skirun_id') new_score = int(request.form.get('rating')) user_id = session.get('logged_in') description = request.form.get('description') rating = Rating.query.filter(Rating.user_id == user_id, Rating.skirun_id == skirun_id).first() # if the user rating for the skirun is already in the system, update rating # if not, add a new rating to the skirun page if rating: rating.rating = new_score rating.comment = description db.session.commit() else: rating = Rating(skirun_id=skirun_id, user_id=user_id, rating=new_score, comment=description) db.session.add(rating) db.session.commit() user_rating = rating.to_dict() return jsonify({'new_rating': user_rating})
def add_rating_to_db(): """Add user rating to database""" user_rating = request.form.get("rating") user_id = session["logged_in_user_id"] movie_id = request.form.get("movie_id") # Check to see if rating already exists in the database # If it's not there, .first() will return None rating = Rating.query.filter(Rating.user_id == user_id, Rating.movie_id == movie_id).first() # If the rating does not already exist, add it to the database if not rating: rating = Rating(user_id=user_id, movie_id=movie_id, score=user_rating) db.session.add(rating) db.session.commit() flash("Added rating.") return redirect("/movies/" + movie_id) # If the rating already exists in the database for that user # update the rating to reflect the new score else: rating.score = user_rating db.session.commit() flash("Updated rating.") return redirect("/movies/" + movie_id)
class TestRating(unittest.TestCase): def setUp(self): self.default_rating_a = Rating() self.default_rating_b = Rating() self.custom_rating = Rating(mu=2., sigma=3.) self.default_rating_a_json_dict = { 'mu': self.default_rating_a.mu, 'sigma': self.default_rating_a.sigma, } def test_trueskill_rating(self): self.assertEqual(trueskill.Rating(mu=2., sigma=3.), self.custom_rating.trueskill_rating()) def test_from_trueskill(self): self.assertEqual( Rating.from_trueskill(trueskill.Rating(mu=2., sigma=3.)), self.custom_rating) self.assertEqual(Rating.from_trueskill(trueskill.Rating()), self.default_rating_a) def test_dump(self): self.assertEqual(self.default_rating_a.dump(), self.default_rating_a_json_dict) def test_load(self): self.assertEqual(Rating.load(self.default_rating_a_json_dict), self.default_rating_a)
class TestRating(unittest.TestCase): def setUp(self): self.default_rating_a = Rating() self.default_rating_b = Rating() self.custom_rating = Rating(mu=2., sigma=3.) self.default_rating_a_json_dict = { 'mu': self.default_rating_a.mu, 'sigma': self.default_rating_a.sigma, } def test_trueskill_rating(self): self.assertEqual(trueskill.Rating(mu=2., sigma=3.), self.custom_rating.trueskill_rating()) def test_from_trueskill(self): self.assertEqual(Rating.from_trueskill(trueskill.Rating(mu=2., sigma=3.)), self.custom_rating) self.assertEqual(Rating.from_trueskill(trueskill.Rating()), self.default_rating_a) def test_dump(self): self.assertEqual(self.default_rating_a.dump(), self.default_rating_a_json_dict) def test_load(self): self.assertEqual(Rating.load(self.default_rating_a_json_dict), self.default_rating_a)
def rating_successful(): """Process new rating and redirect to movie profile page.""" score = request.form.get("rating") user_email = session["email"] timestamp = datetime.now() movie_id = request.form.get("movie_id") # Query the DB for the user id, using the email from the session user_id = db.session.query(User).filter(User.email == user_email).one().user_id count_ratings = db.session.query(Rating).filter(Rating.user_id == user_id, Rating.movie_id == movie_id).count() if count_ratings == 0: rating = Rating(user_id=user_id, movie_id=movie_id, score=score, timestamp=timestamp) db.session.add(rating) db.session.commit() flash("Successfully added rating!") elif count_ratings == 1: rating = db.session.query(Rating).filter(Rating.user_id == user_id, Rating.movie_id == movie_id) rating.score = score db.session.commit() flash("Successfully updated rating!") return redirect('/movies/' + movie_id)
def test_update_player(self): self.assertEquals(self.norcal_dao.get_player_by_id(self.player_1_id), self.player_1) self.assertEquals(self.norcal_dao.get_player_by_id(self.player_2_id), self.player_2) self.assertEquals(self.norcal_dao.get_player_by_id(self.player_3_id), self.player_3) player_1_clone = Player(name='gaR', aliases=['gar', 'garr'], ratings={ 'norcal': Rating(), 'texas': Rating() }, regions=['norcal', 'texas'], id=self.player_1_id) player_1_clone.name = 'garrr' player_1_clone.aliases.append('garrr') del player_1_clone.ratings['texas'] self.assertNotEquals( self.norcal_dao.get_player_by_id(self.player_1_id), player_1_clone) self.norcal_dao.update_player(player_1_clone) self.assertNotEquals( self.norcal_dao.get_player_by_id(self.player_1_id), self.player_1) self.assertEquals(self.norcal_dao.get_player_by_id(self.player_2_id), self.player_2) self.assertEquals(self.norcal_dao.get_player_by_id(self.player_3_id), self.player_3) self.assertEquals(self.norcal_dao.get_player_by_id(self.player_1_id), player_1_clone)
def processing_user_score(): """Records new rating or updates existing rating""" user_score = request.args.get("score") #for user_id and movie_id # if score is Null create new rating in db +flash "u ranked the movie!" # else: update score in db + flash # add to db # commit rating_in_db = db.session.query( Rating.score).filter((Rating.movie_id == movie_id) & (Rating.user_id == user_id)).first() if not rating_in_db: flash("Yay you've rated this movie!") rating_in_db = Rating(user_id=user_id, movie_id=movie_id, user_score=score) db.session.add(rating_in_db) else: flash("We've updated your score for this movie!") rating_in_db.score = int(user_score) db.session.commit() return redirect("/movies" + str(movie_id))
def add_rating(movie_id): """ user adds a rating to a movie """ # gets a score form the user throu the form score = request.form.get("score") if 'user_id' in session: check_rating = db.session.query(Rating).filter( Rating.user_id == session['user_id'], Rating.movie_id == movie_id).first() if check_rating is None: # adds a rating to a movie new_rating = Rating(score=score, movie_id=movie_id, user_id=session['user_id']) db.session.add(new_rating) db.session.commit() return redirect('/') else: # updates an existing rating to a movies new_rating = Rating.query.filter_by( movie_id=movie_id, user_id=session['user_id']).first() new_rating.score = score db.session.add(new_rating) db.session.commit() return redirect('/') else: return redirect("/log-in")
def rate_product(product_id): score = int(request.form["score"]) comment = request.form["comment"] user_id = session.get("user_id") if not user_id: raise Exception("You are not logged in.") rating = Rating.query.filter_by(user_id=user_id, product_id=product_id).first() # comment = Rating.query.filter_by(user_id=user_id, product_id=product_id).first() if rating: rating.score = score flash("Your rating has been updated!") else: rating = Rating(user_id=user_id, product_id=product_id, score=score) flash("Your rating has been added!") db.session.add(rating) if comment: rating.comment = comment flash("Your comment has been updated!") else: comment = Rating(user_id=user_id, product_id=product_id, comment=comment) flash("Your commment has been added!") db.session.add(comment) db.session.commit() return redirect("/product/%s" % product_id)
def test_calc_avg_star_rating(self): rating1 = Rating(rating_id=1, stars=4, comments="abc") rating2 = Rating(rating_id=3, stars=2, comments="def") rating3 = Rating(rating_id=3, stars=3, comments="ghi") ratings = [rating1, rating2, rating3] self.assertEqual(calc_avg_star_rating(ratings), 3)
def processing_user_score(): """Records new rating or updates existing rating""" user_score = request.args.get("score") #for user_id and movie_id # if score is Null create new rating in db +flash "u ranked the movie!" # else: update score in db + flash # add to db # commit rating_in_db = db.session.query(Rating.score).filter((Rating.movie_id == movie_id) & (Rating.user_id == user_id)).first() if not rating_in_db: flash("Yay you've rated this movie!") rating_in_db = Rating(user_id=user_id, movie_id=movie_id, user_score=score) db.session.add(rating_in_db) else: flash("We've updated your score for this movie!") rating_in_db.score = int(user_score) db.session.commit() return redirect("/movies" + str(movie_id))
def load_data(): """pull data from API and load into db""" page_num = 1 # if type(num) == int: # url = "https://refugerestrooms.org:443/api/v1/restrooms.json?page=1&per_page=" + str(page_num) # else: # pass while True: url = "https://www.refugerestrooms.org:443/api/v1/restrooms.json?per_page=100&page=" + str( page_num) results = [] response = requests.get(url) if response.status_code == 200: results = response.json() page_num += 1 # loop thru json data for v in results: # add bathroom and location b = Bathroom(name=v['name'], unisex=v['unisex'], accessible=v['accessible'], changing_table=v['changing_table']) db.session.add(b) db.session.commit() # add location if v['latitude'] == None or v['longitude'] == None: v['latitude'] = 0.00 v['longitude'] = 0.00 l = Location(bathroom_id=b.bathroom_id,street=v['street'], city=v['city'], state=v['state'], \ country=v['country'], latitude=v['latitude'], longitude=v['longitude'], directions=v['directions']) db.session.add(l) db.session.commit() # add comment if len(v['comment']) > 1: c = Comment(comment=v['comment'], bathroom_id=b.bathroom_id, user_id=0) db.session.add(c) db.session.commit() # add ratings if v['downvote'] == 1: r = Rating(bathroom_id=b.bathroom_id, user_id=0, score=2) db.session.add(r) db.session.commit() elif v['upvote'] == 1: r = Rating(bathroom_id=b.bathroom_id, user_id=0, score=5) db.session.add(r) db.session.commit() time.sleep(1) else: break return "finished loading data"
def setUp(self): self.player_1_id = ObjectId() self.player_1_name = 'gaR' self.player_1_aliases = ['gar', 'garr', 'garpr'] self.player_1_rating = { 'norcal': Rating(), 'texas': Rating(mu=10., sigma=1.) } self.player_1_regions = ['norcal', 'texas'] self.player_2_id = ObjectId() self.player_2_name = 'MIOM | SFAT' self.player_2_aliases = ['miom | sfat', 'sfat', 'miom|sfat'] self.player_2_rating = {'norcal': Rating(mu=30., sigma=2.)} self.player_2_regions = ['norcal', 'socal'] self.player_1 = Player(name=self.player_1_name, aliases=self.player_1_aliases, ratings=self.player_1_rating, regions=self.player_1_regions, id=self.player_1_id) self.player_1_missing_id = Player(name=self.player_1_name, aliases=self.player_1_aliases, ratings=self.player_1_rating, regions=self.player_1_regions) self.player_2 = Player(name=self.player_2_name, aliases=self.player_2_aliases, ratings=self.player_2_rating, regions=self.player_2_regions, id=self.player_2_id) self.player_1_json_dict = { '_id': self.player_1_id, 'name': self.player_1_name, 'aliases': self.player_1_aliases, 'ratings': { region: rating.dump() for region, rating in self.player_1_rating.iteritems() }, 'regions': self.player_1_regions, 'merge_children': [self.player_1_id], 'merge_parent': None, 'merged': False, } self.player_1_json_dict_missing_id = { 'name': self.player_1_name, 'aliases': self.player_1_aliases, 'ratings': { region: rating.dump() for region, rating in self.player_1_rating.iteritems() }, 'regions': self.player_1_regions, 'merge_children': [None], 'merge_parent': None, 'merged': False, }
def setUp(self): self.default_rating_a = Rating() self.default_rating_b = Rating() self.custom_rating = Rating(mu=2., sigma=3.) self.default_rating_a_json_dict = { 'mu': self.default_rating_a.mu, 'sigma': self.default_rating_a.sigma, }
def update_trueskill_ratings(region_id, winner=None, loser=None): winner_ratings_dict = winner.ratings loser_ratings_dict = loser.ratings new_winner_rating, new_loser_rating = trueskill.rate_1vs1( winner_ratings_dict[region_id].trueskill_rating(), loser_ratings_dict[region_id].trueskill_rating()) winner_ratings_dict[region_id] = Rating.from_trueskill(new_winner_rating) loser_ratings_dict[region_id] = Rating.from_trueskill(new_loser_rating)
def update_trueskill_ratings(region_id, winner=None, loser=None): winner_ratings_dict = winner.ratings loser_ratings_dict = loser.ratings new_winner_rating, new_loser_rating = trueskill.rate_1vs1( winner_ratings_dict[region_id].trueskill_rating(), loser_ratings_dict[region_id].trueskill_rating() ) winner_ratings_dict[region_id] = Rating.from_trueskill(new_winner_rating) loser_ratings_dict[region_id] = Rating.from_trueskill(new_loser_rating)
def test_get_players_with_similar_alias_match_name(self): player = Player(name='ivanvan', aliases=['asdf'], ratings={ 'norcal': Rating(), 'texas': Rating() }, regions=['norcal', 'texas'], id=ObjectId()) self.norcal_dao.insert_player(player) self.assertEquals( self.norcal_dao.get_players_with_similar_alias('ivanvan'), [player])
def rate_movie(movie_id): if session.get('logged_in_user') is None: flash("You must be logged in to rate a movie. Log in now!") return redirect('/login') else: user_id = session['logged_in_user'] rating = request.args.get('rating') rating_row = Rating.get_rating(movie_id, user_id) if rating_row is None: Rating.create_new_rating(movie_id, user_id, rating) else: rating_row.update_rating(rating) flash("Your rating has been successfully received!") return redirect('/movies/%s' % movie_id)
def get_movie_info(movieid): """Show individual movie info""" movie = Movie.query.filter_by(movie_id=movieid).one() user_r = Rating.get_rating_by_userid_movieid(session['User'], movieid) avg = Rating.avg_rating(movie_id=movieid) predicted_user_rating = "N/A" if not user_r and session['User']: predicted_user_rating = Rating.predict_rating(session["User"], movieid) return render_template("movie_info.html", movie= movie, prediction=predicted_user_rating, avg=avg)
def add_a_rating(): """Add a rating to a movie.""" if not session["user_id"]: return redirect("/login") else: movie_id = request.form.get("movie_id") rating = request.form.get("score") user_id = session["user_id"] user_movie_rating = Rating.query.filter_by(movie_id=movie_id, user_id=user_id).first() if user_movie_rating: message = Markup("You have already rated this movie. \ This has updated your previous rating.") flash(message) user_movie_rating.score = rating db.session.add(user_movie_rating) db.session.commit() return redirect("/movies") else: new_rating = Rating(user_id=user_id, movie_id=movie_id, score=rating) db.session.add(new_rating) db.session.commit() message = Markup("Your rating has been successfully added!") flash(message) return redirect("/movies")
def score_a_movie(): """Updates or enters a movie score, using a user's session id""" score = request.form.get('score') movie_id = request.form.get('movie_id') if int(score) >= 1 and int(score) <= 5: try: db_rating = Rating.query.filter( Rating.user_id == session['user_id'], Rating.movie_id == movie_id).one() db_rating.score = score db.session.commit() flash('You updated your score to ' + str(score)) except NoResultFound: rating = Rating(user_id=session["user_id"], movie_id=movie_id, score=score) db.session.add(rating) db.session.commit() flash('You rated the movie ' + str(score)) return redirect('/movies') else: flash("Not a valid score - please score between 1 and 5!") return redirect('/movie/' + str(movie_id))
def rating_info(movie_id): """Update or insert user rating into db and reload the movie info page""" score = request.form.get("score") user_id = session['user_id'] rating_exists = Rating.query.filter_by(user_id = user_id, movie_id = movie_id).first() #if the rating exists, update, otherwise add it to the database. if rating_exists: rating_exists.update_rating(movie_id, user_id, score) else: Rating.add_rating(movie_id, user_id, score) return redirect('/movies/' + str(movie_id))
def view_movie(id): #id = movie.id user_id = g.user_id if g.user_id: movie = Movie.search_movie(id) ratings = Rating.search_rating(movie.id, user_id.id) beratement = None if ratings == None: ratings = movie.ratings rating_nums = [] user_rating =None for r in ratings: rating_nums.append(r.rating) avg_rating = float(sum(rating_nums))/len(rating_nums) prediction = User.predict_rating(movie.id, user_id.id) the_eye = db_session.query(User).filter_by(email="*****@*****.**").one() eye_rating = db_session.query(Rating).filter_by(user_id = the_eye.id, movie_id = id).first() if not eye_rating: eye_rating = User.predict_rating(movie.id, the_eye.id) print eye_rating else: eye_rating = eye_rating.rating if prediction: difference = abs(eye_rating - prediction) messages = [ "I suppose you don't have such bad taste after all.", "I regret every decision that I've ever made that has brought me to listen to your opinion.", "Words fail me, as your taste in movies has clearly failed you.", "That movie is great. For a clown to watch. Idiot.",] beratement = messages[int(difference)] return render_template("view_movie.html", movie=movie, average=avg_rating, user_rating=user_rating, prediction=prediction, ratings = ratings, beratement=beratement) else: return render_template("view_movie.html", movie = movie, ratings=ratings) return render_template("")
def make_rating(movieid): """Allow user to rate movie or update rating""" rating = request.form.get("rating") user_r = Rating.get_rating_by_userid_movieid(session['User'], movieid) if(user_r): user_rating = Rating.query.filter_by(user_id=session['User'], movie_id=movieid).one() user_rating.score = rating else: Rating.add_new_rating(session['User'], movieid, rating) db.session.commit() return redirect("/movies/{}".format(movieid))
def rate_movie(movie_id): """Rate a movie.""" # Grab user score from form user_score = int(request.form.get('rating_select')) # Grab user_id via session user_id = User.query.filter(User.email == session['username']).one().user_id # Grab user's list of ratings for the movie user_rating = Rating(movie_id=movie_id, user_id=user_id, score=user_score) # Check to see if a new rating passed in, or an update if request.form.get('rating_status') == 'add_rating': db.session.add(user_rating) elif request.form.get('rating_status') == 'update_rating': stored_rating = Rating.query.filter(Rating.movie_id == movie_id, Rating.user_id == user_id).one() stored_rating.score = user_score # Commit changes to ratings table db.session.commit() avg_rating = float(request.form.get('average')) # Query for updated list of movie ratings movie = Movie.query.filter(Movie.movie_id == movie_id).one() return render_template("movie_details.html", movie=movie, is_rated=True, user_rating=user_rating, average=avg_rating, prediction=None)
def rate_movie(): """Rates movie from the movie_info page if user is logged in.""" if 'user_id' in session: movie_id = request.form.get("movie_id") user_id = session['user_id'] score = request.form.get("new_rating") if db.session.query(Rating).filter( Rating.movie_id == movie_id, Rating.user_id == user_id).count() == 0: new_rating = Rating(movie_id=movie_id, user_id=user_id, score=score) db.session.add(new_rating) else: update = db.session.query(Rating).filter( Rating.movie_id == movie_id, Rating.user_id == user_id).first() update.score = score db.session.commit() flash("Success! Your rating has been added!") return redirect("/") else: flash("Please log in!") return redirect("/login")
def add_notes_to_rating(): """User saves notes to db when rating landmark from the landmark details page.""" score = request.form.get("score") notes = request.form.get("notes") landmark_id = request.form.get("landmark_id") user_id = session['user_id'] possible_notes = Rating.query.filter( Rating.user_id == user_id, Rating.landmark_id == landmark_id).first() if possible_notes: possible_notes.user_notes_for_landmark = notes db.session.commit() return "Your review has been updated." else: new_notes = Rating(user_score=score, user_notes_for_landmark=notes, landmark_id=landmark_id, user_id=user_id) db.session.add(new_notes) db.session.commit() return "Review saved."
def rate_landmark(): """User rates landmark from the landmark details page.""" score = request.form.get("score") landmark_id = request.form.get("landmark_id") user_id = session['user_id'] # Create a possible_rating object to query if user_id AND landmark_id is in the ratings table possible_rating = Rating.query.filter( Rating.user_id == user_id, Rating.landmark_id == landmark_id).first() # If this score does not yet exist, we will add to the session database. # If this score already exists, we will update the value of the existing score. if possible_rating: possible_rating.user_score = score db.session.commit() return "Your rating has been updated." else: # Instantiate new rating to add to the user database new_rating = Rating(user_score=score, landmark_id=landmark_id, user_id=user_id) db.session.add(new_rating) db.session.commit() return "Rating saved."
def load_ratings(): """Load ratings from u.data into database. Data looks like: user_id \t movie_id \t score \t timestamp. """ print "Ratings" Rating.query.delete() for i, row in enumerate(open("seed_data/u.data")): row = row.rstrip() user_id, movie_id, score = row.split("\t")[:3] rating = Rating(user_id=user_id, movie_id=movie_id, score=score, ) db.session.add(rating) if i % 1000 == 0: print i # Commit every 1000 rows to increase performance # and prevent thrashing. db.session.commit() db.session.commit()
def process_rating(movie_id): #If a user is logged in, let them add/edit a rating rating = request.form.get("rating") current_email = session['username'] user_id = db.session.query(User).filter_by(email=current_email).one().user_id try: new_score = db.session.query(Rating).filter_by(user_id=user_id, movie_id=movie_id).one() except NoResultFound: new_rating = Rating(user_id=user_id, movie_id=movie_id, score=rating) db.session.add(new_rating) db.session.commit() return redirect("/movies/" + str(movie_id)) new_score.score = rating db.session.commit() return redirect("/movies/" + str(movie_id))
def load_ratings(): """Load ratings from u.data into database.""" print("Ratings") # Delete all rows in table, so if we need to run this a second time, # we won't be trying to add duplicate users Rating.query.delete() # Read u.user file and insert data for row in open("seed_data/u.data"): row = row.rstrip() user_id, movie_id, score, timestamp = row.split("\t") user_id = int(user_id) movie_id = int(movie_id) score = int(score) rating = Rating(movie_id=movie_id, user_id=user_id, score=score) # We need to add to the session or it won't ever be stored db.session.add(rating) # Once we're done, we should commit our work db.session.commit()
def load_ratings(rating_filename): """Load ratings from u.data into database.""" print("Ratings") for i, row in enumerate(open(rating_filename)): row = row.rstrip() user_id, movie_id, score, timestamp = row.split("\t") user_id = int(user_id) movie_id = int(movie_id) score = int(score) # We don't care about the timestamp, so we'll ignore this rating = Rating(user_id=user_id, movie_id=movie_id, score=score) # We need to add to the session or it won't ever be stored db.session.add(rating) # provide some sense of progress if i % 1000 == 0: print(i) # An optimization: if we commit after every add, the database # will do a lot of work committing each record. However, if we # wait until the end, on computers with smaller amounts of # memory, it might thrash around. By committing every 1,000th # add, we'll strike a good balance. db.session.commit() # Once we're done, we should commit our work db.session.commit()
def add_or_update_movie_rating(movie_id): """Logged-in user can update or add a new rating.""" new_rating = request.form.get('rating') rating = Rating.query.filter(Rating.user_id == session['user_id'], Rating.movie_id == movie_id).first() if rating: # Flask/SQLAlchemy equivalent of UPDATE rating.score = new_rating db.session.add(rating) db.session.commit() flash("Rating updated!") else: ## Flask/SQLAlchemy equivalent of INSERT user_rating = Rating(score=new_rating, user_id=session['user_id'], movie_id=movie_id) db.session.add(user_rating) db.session.commit() flash("New rating added!") return redirect('/movies')
def add_rating(movie_id): """Adds new rating to db or updates existing rating for user.""" new_score = request.form.get("score") try: new_score = int(new_score) except ValueError: flash('This is not a valid rating.') if new_score < 1 or new_score > 5: flash('This is not a valid rating.') else: user = session['user_id'] rating = Rating.query.filter(Rating.movie_id == movie_id, Rating.user_id == user).first() # print q if rating: #if list is not empty rating.score = new_score db.session.commit() flash("Your rating has been updated") else: new_movie_rating = Rating(score=new_score, movie_id=movie_id, user_id=user) db.session.add(new_movie_rating) db.session.commit() flash("Your rating has been added") return redirect('/movies/' + str(movie_id))
def load_ratings(): """Load ratings from u.data into database.""" # Prevent double-adding ratings Rating.query.delete() # Read u.user file and insert data f = open("seed_data/u.data") for row in f: row = row.rstrip() user_id, movie_id, score = re.split(r'\t+', row)[:3] rating = Rating(user_id=user_id, movie_id=movie_id, score=score) # We need to add to the session or it won't ever be stored db.session.add(rating) # Close file f.close() # Once we're done, we should commit our work db.session.commit()
def create_rating(user, movie, score): rating = Rating(user=user, movie=movie, score=score) db.session.add(rating) db.session.commit() return rating
def load_ratings(): """Load ratings from u.data into database.""" print("Ratings") Rating.query.delete() for row in open("seed_data/u.data"): row = row.rstrip() #print(row) user_id, movie_id, score, timestamp = row.split('\t') user_id = int(user_id) movie_id = int(movie_id) score = int(score) # print(rating_id) # print(movie_id) # print(user_id) # print(score) rating = Rating(movie_id=movie_id, user_id=user_id, score=score) # print(rating) db.session.add(rating) db.session.commit()
def rate_movie(id): rating_number = int(request.form['rating']) user_id = session['user_id'] rating = db_session.query(Rating).filter_by(user_id=user_id, movie_id=id).first() if not rating: flash("Rating added") rating = Rating(user_id=user_id, movie_id=id) db_session.add(rating) else: flash("Rating updated") rating.rating = rating_number db_session.commit() return redirect(url_for("view_movie", id=id))
def submit_rating(): # get our userid off the session user_id = session.get('user_id', None) if user_id is None: flash('You must be logged in to rate a movie') return redirect('/') score = request.form.get("score") movie_id = request.form.get("movie_id") # Search DB to see if this user already rated this movie # movie_title = Movie.query.filter(Movie.movie_id == movie_id).first().title prior_rating = Rating.query.filter((Rating.movie_id == movie_id) & (Rating.user_id == user_id)).first() # movie_query = Rating.query.filter(Rating.movie_id == movie_id) # r = movie_query.filter(Rating.user_id == user_id).first() if prior_rating is None: # add a new rating rating = Rating(user_id=user_id, movie_id=movie_id, score=score) db.session.add(rating) db.session.commit() # flash a success message flash("Thanks for rating {}!".format(rating.movie.title)) return redirect(f"/movies/{rating.movie.movie_id}") # check to see if this user already submitted a rating prior_rating.score = score db.session.commit() flash("We updated your rating for {}!".format(prior_rating.movie.title)) return redirect(f"/movies/{prior_rating.movie.movie_id}")
def movie_detail_process(movie_id): """Add/edit a rating.""" # Get form variables score = int(request.form["score"]) user_id = session.get("user_id") if not user_id: raise Exception("No user logged in.") # Check for an existing rating rating = Rating.query.filter_by(user_id=user_id, movie_id=movie_id).first() # Update an existing rating or if there isn't one yet, create one. if rating: rating.score = score flash("Rating updated.") else: rating = Rating(user_id=user_id, movie_id=movie_id, score=score) flash("Rating added.") db.session.add(rating) db.session.commit() return redirect(f"/movies/{movie_id}")
def drug_details_process(): """Add/edit a rating.""" spl_set_id = session.get('spl_set_id') thisdrug = Drug.query.get(spl_set_id) score = int(request.form["score"]) comment = request.form["comment"] side_effect = request.form.getlist('side_effect') user_id = session.get("user_id") rating = Rating.query.filter_by(user_id=user_id, spl_set_id=spl_set_id).first() if not rating: rating = Rating(user_id=user_id, spl_set_id=spl_set_id) rating.score = score rating.comment = comment rating.reset_side_effect() for item in side_effect: rating.add_side_effect(item) db.session.add(rating) db.session.commit() return redirect("/rate_drug?spl_set_id=%s" % spl_set_id)
def display_user_details(user_id): display_user = User.query.get(user_id) rating_list = Rating.get_user_ratings(user_id) # print "*******************" , movie_list # for rating in rating_list: # print rating.movie.title return render_template("user_details.html", display_user=display_user, rating_list=rating_list)
def rating(): if not g.user_id: flash("You have to be logged in to rate a movie.") return redirect(redirect_url()) else: user_id = session['user_id'] value = int(request.form["rating"]) movie_id = request.form['movie_id'] rating = db_session.query(Rating).filter(Rating.user_id==user_id).filter(Rating.movie_id==movie_id).first() if not rating: flash("Your rating has been added") rating = Rating(user_id=user_id, movie_id=movie_id) db_session.add(rating) else: flash("Your rating has been updated") rating.rating=value db_session.commit() return redirect (url_for('movie', id=movie_id))
def movie_details(movie_id): movie_id = int(movie_id) movie = Movie.get(movie_id) title = movie["title"] genres = movie["genres"] genre = ", ".join(genres) imdb = movie["imdb_url"] movie_id = movie["_id"] rating_records = Rating.get_many(movie_id) ratings = [ rec['rating'] for rec in rating_records ] avg = float(sum(ratings))/len(ratings) return render_template("movie_details.html", title=title, genre=genre, avg=avg, imdb=imdb, movie=movie)
def rate_movie(movie_id, value): movie = get_movie(movie_id) # rating = Rating(movie_id, value, 0) # print rating, '$'*10 # print get_rating(movie_id, 0) update = Rating.update_rating(movie_id, value) # db.ratings.update({"movie_id": movie_id, "user_id": 0}, # {"$set": {"rating": rating}}, upsert=True) print "You rated movie %d: %s at %d stars."%(\ movie_id, movie.title, value)
def add_rating(): #get movie from search in movie_prof.html movie_id = int(request.form.get("id")) movie_from_wall = request.form.get("rating_from_wall") user_id = int(session["user"].id) not_interested = request.form.get("not_interested") rating = dbsession.query(Rating).filter_by(user_id = user_id, movie_id=movie_id).first() if not_interested: # add new 0 rating score = 0 review = "" else: score = int(request.form.get("star_rating")) review = request.form.get("movie_review") if not review: review = "" if not rating: # add new rating rating = Rating(movie_id = movie_id, user_id = user_id, rating = score, review = review) else: # update existing rating rating.rating = score rating.review = review dbsession.add(rating) dbsession.commit() clear_user_cache() ## flash message that it's been added? if movie_from_wall: return redirect("/wall") else: return redirect("/movie_prof?id=%d" % movie_id)
def home(): movie_ids=[] ratings=[] while len(movie_ids) < 10: movie_id = randint(1,1682) movie = Movie.get(movie_id) movie_ids.append(movie) movie_id = movie["_id"] rating_records = Rating.get_many(movie_id) rating = [ rec['rating'] for rec in rating_records ] avg = float(sum(rating))/len(rating) ratings.append(avg) return render_template("potato.html", ratings=ratings, movie_ids=movie_ids)
def get_rating(movie_id, user_id): record = Rating.get(movie_id, user_id) if record: return record
def rate_movie(id): rating = request.form['rating'] user_id = g.user_id rating_id = Rating.new(id, user_id.id, rating) return redirect("/profile")
def display_movie_details(movie_id): display_movie = Movie.query.get(movie_id) rating_list = Rating.get_movie_ratings(movie_id) user_id = session.get('logged_in_user') if user_id: rating = Rating.get_rating(movie_id, user_id) else: rating = None # rating = Rating.get_rating(movie_id, user_id) rating_scores = [r.score for r in rating_list] avg_score = float(sum(rating_scores)) / len(rating_scores) prediction = None if (not rating) and user_id: user = User.query.get(user_id) if user: print "~~~~~Current movie:", display_movie prediction = user.predict_rating(display_movie) if prediction: # User hasn't scored - use prediction if there is one effective_rating = prediction elif rating: # User has already scored - use that effective_rating = rating.score else: # User hasn't scored - prediction not possib;e effective_rating = None # Get the eye's rating using prediction or the real rating the_eye = User.query.filter_by(email="*****@*****.**").one() eye_rating = Rating.query.filter_by( user_id=the_eye.user_id, movie_id=display_movie.movie_id).first() if eye_rating is None: eye_rating = the_eye.predict_rating(display_movie) else: eye_rating = eye_rating.score if eye_rating and effective_rating: difference = abs(eye_rating - effective_rating) else: # We couldn't get an eye rating, so we'll skip difference difference = None BERATEMENT_MESSAGES = [ "I suppose you don't have such bad taste after all.", "I regret every decision that I've ever made that has brought me" + " to listen to your opinion.", "Words fail me, as your taste in movies has clearly failed you.", "That movie is great. For a clown to watch. Idiot.", "Words cannot express the awfulness of your taste." ] if difference is not None: beratement = BERATEMENT_MESSAGES[int(difference)] else: beratement = None print "beratement:", beratement return render_template("movie_details.html", display_movie=display_movie, rating_list=rating_list, user_rating=rating, average=avg_score, prediction=prediction, beratement=beratement)
def test_load(self): self.assertEqual(Rating.load(self.default_rating_a_json_dict), self.default_rating_a)
def test_from_trueskill(self): self.assertEqual(Rating.from_trueskill(trueskill.Rating(mu=2., sigma=3.)), self.custom_rating) self.assertEqual(Rating.from_trueskill(trueskill.Rating()), self.default_rating_a)
def display_user_details(user_id): display_user = User.query.get(user_id) rating_list = Rating.get_user_ratings(user_id) return render_template("user_details.html", display_user=display_user, rating_list=rating_list)