def authenticate_user(): """checks to see if the user is in the database and checks password""" #TODO: More sophisticated authenication process. Hash passwords, etc. IMPORTANT # for deployment. # gets email and password email = request.form.get("email") password = request.form.get("password") user = model.get_user_by_email(email) # if email not in the database, redirects to a sign up page. if user == None: flash("Please sign up!") return redirect("/new_user") # if password does not match what is in the database, asks user to try again. if user.password != password: flash("The password you entered is incorrect. Please try again.") return redirect("/") # adds email to session. Redirects to run_log. flask_session["email"] = model.get_user_by_email(email).email flash("Successfully logged in!") return redirect("/user_landing")
def add_goal(): """Adds a goal to the database when the user submits the new goal form.""" user = model.get_user_by_email(flask_session["email"]) goal = request.form.get("goal") fitness_level = request.form.get("fitness_level") run_length_history = request.form.get("run_length_history") set_date = datetime.now() race_data = request.form.get("race") if race_data != None: race_data = json.loads(race_data) race_url = str(race_data[0]) event_date = datetime.strptime(str(race_data[1]), "%Y-%m-%dT%H:%M:%S.%fZ") id_for_api = str(race_data[2]) new_goal = model.Goal(user_id = user.id, description=goal, fitness_level=fitness_level, run_length_history=run_length_history, set_date=set_date, race_url = race_url, event_date = event_date, id_for_api = id_for_api) else: goal_date = request.form.get("goal_date_no_race") goal_date = datetime.strptime(goal_date, "%Y-%m-%d") new_goal = model.Goal(user_id = user.id, description=goal, fitness_level=fitness_level, run_length_history=run_length_history, set_date=set_date, event_date = goal_date) model.insert_new_goal(new_goal) goal_obj = model.get_most_recent_goal(user) # Adding subgoals for subgoal in model.subgoal_dictionary[goal_obj.description]: subgoal_to_add = model.Subgoal(goal_id = goal_obj.id, description = subgoal) model.insert_new_subgoal(subgoal_to_add) return redirect("/goals")
def update_goal(): """Will register a subgoal or goal as complete.""" user = model.get_user_by_email(flask_session["email"]) goal_id = request.args.get("goal_id") current_goal = model.get_goal_by_id(goal_id) # list of all subgoals associated with the goal we are viewing. possible_subgoals = model.get_subgoals_by_goal_id(goal_id) # creating a list of subgoals to mark as completed. subgoal_to_commit = [] for subgoal in possible_subgoals: subgoal_id = request.args.get(subgoal.description) # If the box is checked, it will register the subgoal as complete. if subgoal_id != None: subgoal_obj = model.get_subgoal_by_id(int(subgoal_id)) subgoal_obj.date_completed = datetime.now() model.sqla_session.commit() # Determines if the goal was marked as complete. If it was, it updates the database. goal_complete = request.args.get("final_goal") if goal_complete != None: current_goal.date_completed = datetime.now() model.sqla_session.commit() #TODO: redirect back to the goal that was being viewed, not to the goal list. return redirect("/goals")
def show_movie(movie_id): cur_movie = model.get_movie(movie_id) ratings = cur_movie.ratings rating_nums = [] user_rating = None user = model.get_user_by_email(session["email"]) for r in ratings: if r.user_id == user.id: user_rating = r rating_nums.append(r.rating) avg_rating = float(sum(rating_nums))/len(rating_nums) # Prediction code: only predict if the user hasn't rated it. prediction = None if not user_rating: prediction = user.predict_rating(cur_movie) # End prediction if session.get("email"): email = True else: email = False # return render_template("movie.html", movie=cur_movie, ratings=ratings,email=email) return render_template("movie.html", movie=cur_movie, ratings=ratings, avg_rating=avg_rating, email=email, prediction=prediction)
def add_route_to_db(): """Adds the new route to the database""" user = model.get_user_by_email(flask_session["email"]) # Getting info from form. route_title = request.form.get("route_title") location_description = request.form.get("location_description") route_distance = request.form.get("route_distance") user_notes = request.form.get("user_notes") map_embed = request.form.get("map_embed") # creating a route object. route = model.Route(user_id = user.id, title = route_title, location_description = location_description, notes = user_notes, distance = route_distance, html_embed = map_embed) # adding object to the database. model.sqla_session.add(route) model.sqla_session.commit() flash("Added Route to Collection") return redirect("/routes")
def get(self): user_email = self.request.get('user_email') user = model.get_user_by_email(user_email) if user: self.response.headers['Content-Type'] = 'image/png' self.response.out.write(user.profile_image) else: self.response.out.write('No image')
def add_run(): # User Object user = model.get_user_by_email(flask_session["email"]) # Getting info from the form. date_run = request.form.get("new_run_date_and_time") date_run = datetime.strptime(date_run, "%Y-%m-%dT%H:%M") zipcode = request.form.get("zipcode") distance = float(request.form.get("distance")) duration = int(request.form.get("duration")) route = request.form.get("route") pre_run = int(request.form.get("pre_run")) during_run = int(request.form.get("during_run")) post_run = int(request.form.get("post_run")) energy = int(request.form.get("energy")) feeling = request.form.get("feeling") location = request.form.get("location") terrain = request.form.get("terrain") route_type = request.form.get("route_type") thoughts = request.form.get("thoughts") instagram_html = request.form.get("instagram_embed") commit_date = datetime.now() if instagram_html == None: instagram_html = "<p></p>" # Creating a new run and adding it to the database. new_run = model.Run(user_id = user.id, date_run = date_run, zipcode=zipcode, approx_dist = distance, approx_time = duration, commit_date = commit_date, route = route) model.insert_new_run(new_run) new_run_object = model.get_latest_run(user) # Creating rating objects. pre_run = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 1, numeric_ans = pre_run) during_run = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 2, numeric_ans = during_run) post_run = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 3, numeric_ans = post_run) energy = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 4, numeric_ans = energy) feeling = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 5, select_ans = feeling) location = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 6, select_ans = location) terrain = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 7, select_ans = terrain) route_type = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 8, select_ans = route_type) thoughts = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 9, text_ans = thoughts) instagram_embed = model.Rating(user_id=user.id, run_id=new_run_object.id, question_id = 10, text_ans = instagram_html) # Adding rating objects to database. ratings = [pre_run, during_run, post_run, energy, feeling, location, terrain, route_type, thoughts, instagram_embed] for rating in ratings: model.sqla_session.add(rating) model.sqla_session.commit() redirect_url = "/view_run.html?run_id=" + str(new_run_object.id) flash("Run Successfully added!") return redirect(redirect_url)
def get(self): user_email = self.request.get('user_email') user = model.get_user_by_email(user_email) self.response.headers['Content-Type'] = 'application/json' response_content = { 'display_name': user.display_name, 'credit': user.credit, 'rating': user.rating } self.response.out.write(json.dumps(response_content))
def new_goal(): """Renders the form the user completes to add a goal.""" if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") user = model.get_user_by_email(flask_session["email"]) page = "goals" return render_template("new_goal.html", user=user, page = page)
def new_run(): """Renders the form the user completes to add a run.""" if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") # The page variable determines which tabs are active. page = "run" user = model.get_user_by_email(flask_session["email"]) routes = model.get_user_routes(user) return render_template("new_run.html", page = page, routes = routes)
def heat_map_data(): user = model.get_user_by_email(flask_session["email"]) runs = model.find_all_runs(user) run_dictionary = {} for run in runs: run_dictionary[(run.date_run - datetime(1970,1,1)).total_seconds()] = run.approx_dist run_dictionary = json.dumps(run_dictionary) return run_dictionary
def commute_profile(): if session['email']: email = session['email'] user_id = model.get_user_by_email(email) startaddrform = request.form.get("depart") destaddrform = request.form.get("destination") starttimeform = request.form.get("starttime") endtimform = request.form.get("endtime") mobileform = request.form.get("mobile") workform = request.form.get("work") homeform = request.form.get("home") model.complete_commute_profile(user_id, startaddrform,destaddrform,starttimeform,endtimform,mobileform,workform,homeform) return redirect(url_for("testmap"))
def view_user_route(): """Lets the user view details about a single route.""" if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") user = model.get_user_by_email(flask_session["email"]) # The page variable determines which tabs are active. page = "route" current_route_id = request.args.get("route_id") current_route = model.get_route_by_id(current_route_id) return render_template("view_route.html", page = page, route = current_route)
def view_route_library(): """Will display the user's collection of routes.""" if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") # The page variable determines which tabs are active. page = "route" user = model.get_user_by_email(flask_session["email"]) routes = model.get_user_routes(user) return render_template("routes.html", page = page, routes = routes)
def after_mood(): user = model.get_user_by_email(flask_session["email"]) number_of_runs = request.args.get("number_of_runs") after_rating_list = model.get_after_ratings(user, runs_to_get = number_of_runs) feelings_ratings = {"name": "Root", "children": [{"name": "After Run", "children": [], "size": 800}], "size": 1000} for i in range (len(after_rating_list)): feelings_ratings["children"][0]["children"].append({"name": str(after_rating_list[i][0]), "size": after_rating_list[i][1], "score": after_rating_list[i][0]}) json_feelings = json.dumps(feelings_ratings) return json_feelings
def set_goals(): """Lists all of the goals the user has set.""" if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") user = model.get_user_by_email(flask_session["email"]) goals = user.goals page = "goals" return render_template("goal_log.html" , goals = goals, goal_dictionary = model.goal_dictionary, page = page)
def review_movie(movie_id): print "#"*80 user = model.get_user_by_email(session.get("email")) print user print "#"*80 user_id = user.id movie_rating = request.form.get("ratings") model.add_movie_rating(user_id=user_id, movie_id=movie_id, rating=movie_rating) cur_movie = model.get_movie(movie_id) ratings = model.get_ratings_by_movie_id(movie_id) email = True return render_template("movie.html", movie=cur_movie, ratings=ratings, email=email)
def commute_profile(): if session['email']: email = session['email'] user_id = model.get_user_by_email(email) startaddrform = request.form.get("depart") destaddrform = request.form.get("destination") starttimeform = request.form.get("starttime") endtimform = request.form.get("endtime") mobileform = request.form.get("mobile") workform = request.form.get("work") homeform = request.form.get("home") start_addr_id, dest_addr_id = model.complete_commute_profile( user_id, startaddrform, destaddrform, starttimeform, endtimform, mobileform, workform, homeform) return redirect( url_for("match") + "?start_addr_id=%d&dest_addr_id=%d" % (start_addr_id, dest_addr_id))
def flare_data(): user = model.get_user_by_email(flask_session["email"]) number_of_runs = request.args.get("number_of_runs") if number_of_runs == None: number_of_runs = 5 during_rating_list = model.get_during_ratings(user, runs_to_get = number_of_runs) feelings_ratings = {"name": "Root", "children": [{"name": "During Run", "children": [], "size": 800}], "size": 1000} for i in range (len(during_rating_list)): feelings_ratings["children"][0]["children"].append({"name": str(during_rating_list[i][0]), "size": during_rating_list[i][1]}) json_feelings = json.dumps(feelings_ratings) return json_feelings
def actually_login(): email = request.form.get("email") password = request.form.get("password") #user = model.session.query(model.User).filter_by(email=temail).first() user = model.get_user_by_email(email, password) if user is None: flash("User does not exist") return redirect(url_for('actually_login')) elif user == "incorrect password": flash("Incorrect password") return redirect(url_for('actually_login')) else: session['email'] = user.email session['id'] = user.id session['logged_in'] = True return redirect(url_for("main_page"))
def display_log(): """Displays links to review the previous runs.""" # TODO PAGINATION? if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") user = model.get_user_by_email(flask_session["email"]) runs = model.find_all_runs_desc(user) number_of_runs = len(runs) # The page variable determines which tabs are active. page = "run" return render_template("run_log.html", user = user, runs = runs, page = page, number_of_runs = number_of_runs)
def signup(): if session.get("username"): return redirect(url_for("search")) if request.method == "POST": username = request.form["username"] email = request.form["email"] password = request.form["password"] password = generate_password_hash(password) if get_user_by_name(username): flash("Пользователь с таким именем уже зарегистрирован!") return redirect(url_for("signup")) elif get_user_by_email(email): flash("Пользователь с такой почтой уже зарегистрирован!") return redirect(url_for("signup")) else: add_user(username, email, password) session["username"] = username return redirect(url_for("search")) return render_template("signup.html")
def register_user(): """Register or sign up user""" #post requests mean they've submitted form on register.html if request.method == 'POST': user_email = request.form.get('email') user_password = request.form.get('password') user_age = int(request.form.get('age')) user_zipcode = request.form.get('zipcode') result = get_user_by_email(user_email) #querying DB for username if result: ##SHOW ALERT, "username exists" flash('That %s already exists. Please login or use a different email' % user_email) return redirect('/register') else: add_user(user_email, user_password, user_age, user_zipcode) flash('%s has been successfully registered and logged in.' % user_email) session['user_id'] = result.user_id return redirect('/') else: # coming from link on homepage.html return render_template("register.html")
def bar_chart(): """Will send the relevant information to the run graph page in order to construct a bar chart that will show the users last five runs.""" number_of_runs = request.args.get("number_of_runs") if number_of_runs == None: number_of_runs = 5 user = model.get_user_by_email(flask_session["email"]) runs = model.get_collection_of_runs(user.id, runs_to_get = number_of_runs) run_list_of_dictionaries = [] #Changing date in order to jsonify for run in runs: run_list_of_dictionaries.append({'date': run[0].strftime("%m-%d-%Y"), 'distance': run[1], "score": run[2]}) json_runs = json.dumps(run_list_of_dictionaries) return json_runs
def view_goal(): """Views a goal that the user previously set.""" # TODO goals should be able to be shown as complete, just like subgoals do at the moment. if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") user = model.get_user_by_email(flask_session["email"]) current_goal_id = request.args.get("goal_id") current_goal = model.get_goal_by_id(current_goal_id) subgoals = model.get_subgoals_by_goal_id(current_goal_id) outstanding_subgoals = model.get_outstanding_subgoal_by_goal_id(current_goal_id) runs_after_date = model.get_runs_after_date(user, current_goal.set_date) possible_matches = [] for subgoal in outstanding_subgoals: for run in runs_after_date: if run.approx_dist >= model.distance_int_dictionary[subgoal.description]: possible_matches.append((subgoal, run)) update_button = False if not current_goal.date_completed: update_button = True days_left = (current_goal.event_date - datetime.now()).days else: days_left = "Goal Complete!" # The page variable determines which tabs are active. page = "goals" return render_template("view_goal.html", goal=current_goal, goal_dictionary = model.goal_dictionary, subgoals = subgoals, update_button = update_button, days_left = days_left, possible_matches = possible_matches, page = page)
def actually_login(): print "something else" email = request.form.get("email") password = request.form.get("password") print password #user = model.session.query(model.User).filter_by(email=temail).first() user = model.get_user_by_email(email, password) if user is None: print "none" flash("User does not exist") return redirect(url_for('actually_login')) #elif user.password != password: elif user == "incorrect password": flash("Incorrect password") print "incorrectpw" return redirect(url_for('actually_login')) else: session['email'] = user.email session['id'] = user.id session['logged_in'] = True print "loggedin???" return redirect(url_for("dashboard"))
def display_ideal(): """"Will display the conditions under which the user experiences the best runs.""" if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") user = model.get_user_by_email(flask_session["email"]) # The page variable determines which tabs are active. page = "ideal" runs = model.find_all_runs(user) # Making a generalization about your running habits only makes sense after a certain number of runs. # If you haven't logged a certain number of runs, it will render a template that # will tell you that this functionality will appear after more runs are logged. if len(runs) < 10: return render_template("go_run.html", page = page) run_dictionary = {} for run in runs: run_dictionary[run.id] = run # Finding user's average score and max score. max_score = 0 average_score = 0 for run_key in run_dictionary.keys(): run_score = model.get_run_score(run_key) if run_score > max_score: max_score = run_score average_score = average_score + run_score average_score = average_score/len(run_dictionary.keys()) # Determining the threshold of what is a "highly rated run" for the indivual user. high_rated_run_threshold = (max_score + average_score) * 0.5 # Building the highly rated dictionary. run_dictionary_high_score = {} for run_key in run_dictionary.keys(): run_score = model.get_run_score(run_key) if run_score >= high_rated_run_threshold: run_dictionary_high_score[run_key] = run_dictionary[run_key] # Finding the average distance of highly rated runs. average_dist_high_rated_runs = 0 for run_key in run_dictionary_high_score.keys(): average_dist_high_rated_runs = average_dist_high_rated_runs + run_dictionary_high_score[run_key].approx_dist average_dist_high_rated_runs = average_dist_high_rated_runs / len(run_dictionary_high_score.keys()) # Finding the average distance of all user runs. average_dist_run = 0 for run_key in run_dictionary.keys(): average_dist_run = average_dist_run + run_dictionary[run_key].approx_dist average_dist_run = average_dist_run / len(run_dictionary.keys()) # Finding the conditions that you prefer. locations = [] terrains = [] routes = [] for run_key in run_dictionary_high_score.keys(): locations.append(model.get_location_by_run_id(run_key).select_ans) terrains.append(model.get_terrain_by_run_id(run_key).select_ans) routes.append(model.get_route_by_run_id(run_key).select_ans) prefered_terrain = {} # iterates through all the terrain conditions. for key in model.terrain_dictionary.keys(): # If the prefered terrain dictionary is empty it adds the key to it. if prefered_terrain == {}: prefered_terrain[key] = (model.terrain_dictionary[key], terrains.count(key)) # If the prefered terrain dictionary is not empty, it adds the terrain we are currently # on if they have the same counts. If the current terrain has a higher count, it replaces the # dictionary with one where the current key is the only key. If the count is less than # what is currently in the dictionary, it moves along. elif terrains.count(key) == terrains.count(prefered_terrain.keys()[0]): prefered_terrain[key] = (model.terrain_dictionary[key], terrains.count(key)) elif terrains.count(key) > terrains.count(prefered_terrain.keys()[0]): prefered_terrain = {} prefered_terrain[key] = (model.terrain_dictionary[key], terrains.count(key)) else: pass prefered_route = {} # Iterates through all the route conditions. for key in model.route_dictionary.keys(): # If the prefered route dictionary is empty it adds the key to it. if prefered_route == {}: prefered_route[key] = (model.route_dictionary[key], routes.count(key)) # If the prefered route dictionary is not empty, it adds the route we are currently # on if they have the same counts. If the current route has a higher count, it replaces the # dictionary with one where the current key is the only key. If the count is less than # what is currently in the dictionary, it moves along. elif routes.count(key) == routes.count(prefered_route.keys()[0]): prefered_route[key] = (model.route_dictionary[key], routes.count(key)) elif routes.count(key) > routes.count(prefered_route.keys()[0]): prefered_route = {} prefered_route[key] = (model.route_dictionary[key], routes.count(key)) else: pass prefered_location = {} # Iterates through all the location conditions. for key in model.location_dictionary.keys(): # If the prefered location dictionary is empty it adds the key to it. if prefered_location == {}: prefered_location[key] = (model.location_dictionary[key], locations.count(key)) # If the prefered location dictionary is not empty, it adds the location we are currently # on if they have the same counts. If the current location has a higher count, it replaces the # dictionary with one where the current key is the only key. If the count is less than # what is currently in the dictionary, it moves along. elif locations.count(key) == locations.count(prefered_location.keys()[0]): prefered_location[key] = (model.location_dictionary[key], locations.count(key)) elif locations.count(key) > locations.count(prefered_location.keys()[0]): prefered_location = {} prefered_location[key] = (model.location_dictionary[key], locations.count(key)) else: pass # Determines the days of the week that tend to have your higher rated runs. weekdays = [] weekday_string_list = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] # makes a list of weekdays with highly rated runs. for run_key in run_dictionary_high_score.keys(): weekdays.append(run_dictionary_high_score[run_key].date_run.weekday()) prefered_weekday = {} for weekday in range(7): if prefered_weekday == {}: prefered_weekday[weekday] = weekdays.count(weekday) elif weekdays.count(weekday) == weekdays.count(prefered_weekday.keys()[0]): prefered_weekday[weekday] = weekdays.count(weekday) elif weekdays.count(weekday) > weekdays.count(prefered_weekday.keys()[0]): prefered_weekday = {} prefered_weekday[weekday] = weekdays.count(weekday) else: pass prefered_weekday_string = {} # creates a dictionary with a the weekdays as strings instead of 0-6. for key in prefered_weekday.keys(): prefered_weekday_string[weekday_string_list[key]] = prefered_weekday[key] prefered_weekday_keys = prefered_weekday.keys() prefered_location_keys = prefered_location.keys() prefered_terrain_keys = prefered_terrain.keys() prefered_route_keys = prefered_route.keys() location_image_dictionary = model.location_badges_dictionary terrain_image_dictionary = model.terrain_badges_dictionary route_image_dictionary = model.route_badges_dictionary weekday_image_dictionary = model.weekday_badges_dictionary return render_template("ideal.html", high_distance = average_dist_high_rated_runs, average_distance = average_dist_run, prefered_terrain = prefered_terrain, prefered_route = prefered_route, prefered_location = prefered_location, prefered_weekday = prefered_weekday_string, page = page, len_day = len(prefered_weekday_string), len_location = len(prefered_location), len_terrain = len(prefered_terrain), len_route = len(prefered_route), prefered_weekday_keys=prefered_weekday_keys, prefered_route_keys = prefered_route_keys, prefered_location_keys = prefered_location_keys, prefered_terrain_keys = prefered_terrain_keys, location_images = location_image_dictionary, terrain_images = terrain_image_dictionary, route_images = route_image_dictionary, weekday_images = weekday_image_dictionary)
def validate_existing_user(item): usernamecase = model.get_user_by_username(item.username) emailcase = model.get_user_by_email(item.email) return not bool(usernamecase) and not bool(emailcase)
def dashboard(): """Displays relevant info for the user, that he or she will see upon logging in.""" if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") user = model.get_user_by_email(flask_session["email"]) runs = model.get_collection_of_runs(user.id, runs_to_get = 4) instagrams = [] for run in runs: instagram = model.get_instagram(run[3]) if len(instagram[0].text_ans) > 20: instagrams.append(instagram[0].text_ans) #looks for more instagrams if the first search didn't return very many if len(instagrams) < 4: instagrams = [] runs = model.get_collection_of_runs(user.id, runs_to_get = 8) for run in runs: instagram = model.get_instagram(run[3]) if len(instagram[0].text_ans) > 20: instagrams.append(instagram[0].text_ans) if len(instagrams) > 4: instagrams = instagrams[:4] #gets outstanding subgoals outstanding_subgoals = model.get_outstanding_subgoals(user) possible_matches = [] for subgoal in outstanding_subgoals: runs_after_date = model.get_runs_after_date(user, subgoal.goal.set_date) for run in runs_after_date: if run.approx_dist >= model.distance_int_dictionary[subgoal.description]: possible_matches.append((subgoal, run)) # gets outstanding goals outstanding_goals = model.get_outstanding_goals(user) possible_goal_matches = [] for goal in outstanding_goals: for run in runs_after_date: if run.approx_dist >= model.distance_int_dictionary[goal.description]: possible_goal_matches.append((goal, run)) # The page variable determines which tabs are active. page = "user_landing" return render_template("user_landing.html", instagrams=instagrams, possible_matches = possible_matches, possible_goal_matches = possible_goal_matches, goal_dictionary = model.goal_dictionary, page = page)
def update_run_on_database(): """Updates the editied run on the database.""" if flask_session.get("email") == None: flash("You must sign in to view that page.") return redirect("/") # Getting all the relevant info. user = model.get_user_by_email(flask_session["email"]) run_id = request.form.get("run_id") run_object = model.get_run_by_id(run_id) date_run = request.form.get("new_run_date_and_time") if date_run == "": date_run = run_object.date_run else: date_run = datetime.strptime(date_run, "%Y-%m-%dT%H:%M") zipcode = request.form.get("zipcode") distance = float(request.form.get("distance")) duration = int(request.form.get("duration")) pre_run = int(request.form.get("pre_run")) during_run = int(request.form.get("during_run")) post_run = int(request.form.get("post_run")) energy = int(request.form.get("energy")) feeling = request.form.get("feeling") location = request.form.get("location") terrain = request.form.get("terrain") route = request.form.get("route") thoughts = request.form.get("thoughts") instagram_html = request.form.get("instagram_embed") # modifying run run_object.zipcode = zipcode run_object.approx_dist = distance run_object.approx_time = duration if date_run != " ": run_object.date_run = date_run model.sqla_session.commit() # Modifying ratings. ratings = model.get_ratings_for_run(run_id) ratings[0].numeric_ans = pre_run ratings[1].numeric_ans = during_run ratings[2].numeric_ans = post_run ratings[3].numeric_ans = energy ratings[4].select_ans = feeling ratings[5].select_ans = location ratings[6].select_ans = terrain ratings[7].select_ans = route model.sqla_session.commit() #checking to see if there are new text entries and commiting them # if they have been updated. instagram_html = request.form.get("instagram_embed") if len(instagram_html)< 20: pass else: ratings[9].text_ans = instagram_html if len(thoughts) < 2 or thoughts == None: pass else: ratings[8].text_ans = thoughts model.sqla_session.commit() redirect_url = "/view_run.html?run_id=" + str(run_id) flash("Run Successfully Updated!") return redirect(redirect_url)
def pie_chart(): """ Will return the data required to the run graph page to create a chart that will show the user the percentage of their runs occur in different locales. """ user = model.get_user_by_email(flask_session["email"]) number_of_runs = request.args.get("number_of_runs") if number_of_runs == None: number_of_runs = 5 location_ratings = model.get_location_ratings(user, runs_to_get = number_of_runs) location_dictionary = {} for rating in location_ratings: if location_dictionary.get(rating.select_ans) == None: location_dictionary[rating.select_ans] = 1 else: location_dictionary[rating.select_ans] = location_dictionary[rating.select_ans] + 1 location_list = [] for each_key in location_dictionary.keys(): location_list.append({"condition": each_key.upper(), "occurances": location_dictionary[each_key], "color": model.location_color_dictionary[each_key] }) terrain_ratings=model.get_terrain_ratings(user, runs_to_get = number_of_runs) terrain_dictionary = {} for rating in terrain_ratings: if terrain_dictionary.get(rating.select_ans) == None: terrain_dictionary[rating.select_ans] = 1 else: terrain_dictionary[rating.select_ans] = terrain_dictionary[rating.select_ans] + 1 terrain_list = [] for each_key in terrain_dictionary.keys(): terrain_list.append({"condition": each_key.upper(), "occurances": terrain_dictionary[each_key], "color": model.terrain_color_dictionary[each_key] }) route_ratings=model.get_route_ratings(user, runs_to_get = number_of_runs) route_dictionary = {} for rating in route_ratings: if route_dictionary.get(rating.select_ans) == None: route_dictionary[rating.select_ans] = 1 else: route_dictionary[rating.select_ans] = route_dictionary[rating.select_ans] + 1 route_list = [] for each_key in route_dictionary.keys(): route_list.append({"condition": each_key.upper(), "occurances": route_dictionary[each_key], "color": model.route_color_dictionary[each_key] }) json_conditions = json.dumps([location_list, terrain_list, route_list]) return json_conditions