def update_user_preference(preference, include): """ Takes id of changed checkbox and updates user_preferences table. :param preference: html ID of checkbox, as 'pref_category-pref_value'. :param include: 0 or 1 to indicate whether checkbox is checked :return: None """ # string parse preference so before first '-' is category and after is value index = preference.find('-') pref_category = preference[0:index] pref_value = preference[index + 1:] # get preference object for this category-value pair, so pref_id can be used # to add/remove UserPreference pref = Preference.query.filter(Preference.pref_category == pref_category, Preference.pref_value == pref_value).one() pref_id = pref.pref_id user = User.query.filter(User.username == session.get("username")).first() user_id = user.user_id if (include == 1): new_user_pref = UserPreference(user_id=user_id, pref_id=pref_id) db.session.add(new_user_pref) # if include == 0, search for record in db, and remove if there (should be) else: user_pref_to_be_removed = UserPreference.query.filter( UserPreference.user_id == user_id, UserPreference.pref_id == pref_id).one() db.session.delete(user_pref_to_be_removed) db.session.commit()
def welcome_register(): """ If person attempts to create a new account, processes their data to create account and log them in. Flashes message of success when complete """ username = request.form.get('username') email = request.form.get('email') password = request.form.get('password') prefs = request.form.getlist('prefs') hashed_pw = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) new_user = User(username=username, email=email, password=hashed_pw) db.session.add(new_user) db.session.commit() user_prefs = Category.query.filter(Category.category_name.in_(prefs)).all() added_user = User.query.filter_by(email=email).first() for item in user_prefs: new_pref = UserPreference(user_id=added_user.user_id, category_id=item.category_id) db.session.add(new_pref) db.session.commit() session['username'] = added_user.username session['user_id'] = added_user.user_id flash("You have successfully created an account!") return redirect("/")
def create_user_preference(user_id, preference_id): """creates and returns a user preference""" user_prence = UserPreference(user_id=user_id, preference_id=preference_id) db.session.add(user_prence) db.session.commit() return user_prence
def load_prefs(): print "Adding Sample User Preference(s)" user_id = User.query.filter_by( email=os.environ['SAMPLE_EMAIL']).first().user_id user_pref = UserPreference(user_id=user_id, category_id=528) db.session.add(user_pref) db.session.commit()
def strava_authorized(): code = request.args.get('code') # or whatever your framework does client = stravalib.client.Client() access_token = client.exchange_code_for_token( client_id=app.config['STRAVA_CLIENT_ID'], client_secret=app.config['STRAVA_CLIENT_SECRET'], code=code) current_user.preferences['strava'] = UserPreference('strava', access_token) db.session.commit() flash("Access to Strava API granted") return redirect(url_for('move_import'))
def edit_user_preferences(): """ Updates user's dietary preferences """ # Get info from newly submitted form (plus session user_id) user_id = session['user_id'] prefs_post = dict(request.form) # Unpack individual preferences from POST request responses new_prefs = [] for pref in prefs_post['prefs[]']: new_prefs.append(pref) # Query database to get comparable lists of categories to allow matching of # new preferences against old preferences new_pref_categories = Category.query.filter( Category.category_name.in_(new_prefs)).all() current_prefs = UserPreference.query.filter_by(user_id=user_id).all() current_pref_categories = UserPreference.query.filter( UserPreference.user_id == user_id).all() #-- Compare old vs. new preferences --# # If an preference is in the new list but not in the old, create a new # UserPreference object in the database. If a preference is in the old list # but not in the new, delete the corresponding UserPreference object from # the database for item in new_pref_categories: if item.category_id in current_pref_categories: continue else: update_pref = UserPreference(user_id=user_id, category_id=item.category_id) db.session.add(update_pref) for pref in current_prefs: if pref.category.category_name in new_prefs: continue else: db.session.delete(pref) db.session.commit() # Fetch new preferences to return & populate in success function updated_pref_ids = db.session.query( UserPreference.category_id).filter_by(user_id=user_id).all() updated_pref_names = db.session.query(Category.category_name).filter( Category.category_id.in_(updated_pref_ids)).all() # Use jinja to dynamically render html formatting for new prefs & feed # html back to template using AJAX call return jsonify( render_template('fetched_preferences.html', new_prefs=updated_pref_names))
def load_user_preferences(user_preference_data): """Load user preferences from file""" UserPreference.query.delete() with open(user_preference_data) as user_prefs: for row in user_prefs: row = row.rstrip() user_id, pref_id = row.split("|") user_id = int(user_id) user_preference = UserPreference(user_id=user_id, pref_id=pref_id) # Add new UserPreference object to the session db.session.add(user_preference) # Commit changes to DB db.session.commit()
def moves(): start_date, end_date = _get_date_range() filter_end_date = end_date + timedelta(days=1) moves = _current_user_filtered(Move.query).filter(Move.date_time >= start_date) \ .filter(Move.date_time < filter_end_date) total_moves_count = moves.count() move_filter = _parse_move_filter(request.args.get('filter')) if move_filter: moves = moves.filter_by(**move_filter) sort = request.args.get('sort') sort_order = request.args.get('sort_order') sort_default = 'date_time' if 'sort' not in current_user.preferences: default_sort_value = {'column': sort_default, 'order': 'desc'} current_user.preferences['sort'] = UserPreference( 'sort', default_sort_value) db.session.commit() if not sort: sort = current_user.preferences['sort'].value['column'] if not sort_order: sort_order = current_user.preferences['sort'].value['order'] if not hasattr(Move, sort): flash("illegal sort field: %s" % sort, 'error') sort = sort_default new_sort_value = {'column': sort, 'order': sort_order} if current_user.preferences['sort'].value != new_sort_value: app.logger.debug("updating sort preference to %s" % new_sort_value) current_user.preferences['sort'].value = new_sort_value db.session.commit() activity_counts = OrderedDict( _current_user_filtered( db.session.query(Move.activity, func.count( Move.id))).filter(Move.date_time >= start_date).filter( Move.date_time < filter_end_date).group_by( Move.activity).order_by(func.count(Move.id).desc())) actual_activities_query = _current_user_filtered( db.session.query(distinct(Move.activity))) if move_filter: actual_activities_query = actual_activities_query.filter_by( **move_filter) actual_activities = set( [activity for activity, in actual_activities_query]) sort_attr = getattr(Move, sort) if not sort_order or sort_order == 'asc': sort_attr = sort_attr.asc() else: sort_attr = sort_attr.desc() if db.engine.name == "postgresql": sort_attr = sort_attr.nullslast() show_columns = {} for column in ('location_address', 'speed_avg', 'speed_max', 'hr_avg', 'ascent', 'descent', 'recovery_time', 'stroke_count', 'pool_length'): attr = getattr(Move, column) base_query = _current_user_filtered( db.session.query(attr).filter(attr != None).filter( Move.date_time >= start_date).filter( Move.date_time < filter_end_date)) if move_filter: base_query = base_query.filter_by(**move_filter) exists_query = db.session.query(literal(True)).filter( base_query.exists()) show_columns[column] = exists_query.scalar() show_columns['activity'] = not move_filter or 'activity' not in move_filter moves = moves.order_by(sort_attr) return render_template('moves.html', start_date=start_date, end_date=end_date, moves=moves, total_moves_count=total_moves_count, activity_counts=activity_counts, actual_activities=actual_activities, show_columns=show_columns, sort=sort, sort_order=sort_order)