def weight(self, fields): weight = Weight(ndb_number=fields[0], sequence_number=fields[1], amount=float(fields[2]), measure_description=fields[3], gram_weight=float(fields[4]), num_data_points=int(fields[5]) if fields[5] else None, standard_deviation=float(fields[6]) if fields[6] else None) weight.food_description_id = \ self.food_description_ndb_number_map[weight.ndb_number] return weight
def _list(self, **kwargs): params = self._parse_parameters(self.FILTER_PARAMS) model_id = kwargs.get('model_id') kwargs['parent'] = params.get('parent') or '' segment = get_segment(model_id, params.get('segment')) kwargs['segment_id'] = segment.id if segment else None class_label, class_query = get_class_label(model_id, params) if class_query: kwargs['class_label'] = class_label opts = self._prepare_show_fields_opts( WeightsCategory, ('short_name', 'name', 'normalized_weight')) categories = WeightsCategory.query.options(*opts).filter_by(**kwargs) extra_fields = {} field_names = [ 'short_name', 'name', 'css_class', 'value', 'segment_id', 'value2' ] if params['test_id']: test_weight = Weight.test_weight(str(params['test_id'])) extra_fields = {'test_weight': test_weight} context = { 'categories': categories, 'weights': _select(Weight, field_names, kwargs, extra_fields) } return self._render(context)
def update_weight_database(): for k, v in { WEIGHT_CATEGORY_NAME: WEIGHT_CATEGORY, WEIGHT_DESCRIPTION_NAME: WEIGHT_DESCRIPTION_TEXT, WEIGHT_WEBSITE_NAME: WEIGHT_WEBSITE_TEXT }.items(): Weight(name=k, weight=v).save()
def add_weight(): data = request.get_json() new_weight = Weight(uid=data['user_id'], weight=data['weight'], date=data['date']) db.session.add(new_weight) db.session.commit() return jsonify({ 'message': 'Weight log added successfully!', 'status': 200 })
def add_weight(doc, username): if username: u1 = User.query.get(username) for elem in doc.xpath('//days/day'): we1 = Weight() we1.wdate = datetime.datetime.strptime(elem.attrib['date'], '%Y-%m-%d') if u1: we1.user_username = u1.username w = False for i in elem: if i.tag=='weight' and i.text: if 'scale' in i.attrib: sc1 = Scale.query.get(unicode(i.attrib['scale'])) if sc1: we1.scale_name = sc1.name we1.weight = unicode(i.text) w = True if i.tag=='comment' and i.text: we1.comment = unicode(i.text) if w: db.session.add(we1) db.session.commit()
def weight(wid=None): from models import Weight, Scale, User import math if not wid and 'wid' in request.args: wid = request.args.get('wid') if wid: # edit weight elem = Weight.query.get(wid) # get min/max for buttons x = Weight.query.order_by(Weight.wdate.desc()).limit(20).all() if x: wmin = int(math.floor(min([i.weight for i in x])) - 1) wmax = int(math.ceil(max([i.weight for i in x])) + 2) else: wmin=70 wmax=75 if elem: # is this weight from logged_in user? or is user admin? if elem.user_username == current_user._user or \ current_user._user == 'admin': form = WeightForm(obj=elem) else: # unauthorized abort(401) else: # add form = WeightForm() # get scales list form.scale_name.choices = [(g.name, g.name) for g in Scale.query.order_by('name')] form.scale_name.choices.insert(0, ("", "Select...")) if form.validate_on_submit(): if not elem: elem = Weight(weight=request.form['weight']) if 'weight' in request.form: elem.weight = request.form['weight'] if 'wdate' in request.form: elem.wdate = datetime.datetime.strptime(request.form['wdate'], '%Y-%m-%d') if 'scale_name' in request.form: elem.scale_name = request.form['scale_name'] elem.user_username = current_user._user db.session.add(elem) db.session.commit() flash('Data saved [%s with %s]' % (elem.wdate, elem.weight), 'info') # write to fitbitapi # u1 = User.query.get(current_user._user) # if u1.fitbit_user_key is not None and \ # u1.fitbit_user_secret is not None: # fitbit_push(u1, elem.wdate, elem.weight) # flash('Data pushed to fitbit', 'info') if elem: if elem.scale_name: form.scale_name.data = elem.scale_name else: u1 = User.query.get(current_user._user) if u1.default_scale_name: form.scale_name.data = u1.default_scale_name return render_template('weight_edit.html', form=form, wrange=range(wmin,wmax),) else: # show table of weights page = request.args.get('page', '') if page.isdigit(): page = int(page) else: page = 1 elements = Weight.query.order_by('wdate desc').filter_by( user_username=unicode(current_user._user)).paginate( page, per_page=10) return render_template('weight_list.html', elements=elements.items, paginate=elements, show_comment=False,)
def home(): print(request.form) user: User = current_user weights = user.weights_dict() steps = user.steps_dict() today = datetime.today() points = [] message = "You can still log your current weight and steps to gain points, make over 10000 steps to make even more points." for weight in weights: if (today.strftime("%m/%d/%y") in weight.values()): points.append(40) message = "Try to make more then 10000 steps tommorow to gain the last 20 points." break for step in steps: if (today.strftime("%m/%d/%y") in step.values()): points.append(40) message = "Try to make more then 10000 steps tommorow to gain the last 20 points." if (step['series'] > 10000): points.append(20) message = "You've done everything for today. A full one hundred points, be proud!!" break le_form = LogExerciseForm(prefix='exercise') le_form.exercise.choices = [(e.id, e.name) for e in Exercise.query.all()] lf_form = LogFoodForm(prefix='food') lf_form.ingredient.choices = [(i.id, i.name) for i in Ingredient.query.all()] w_form = AddWeightForm(prefix='weight') s_form = AddStepsForm(prefix='steps') if lf_form.ingredient.data and lf_form.validate_on_submit(): food_log = FoodLog(grams=lf_form.grams.data) food_log.user = current_user food_log.ingredient_id = lf_form.ingredient.data db.session.add(food_log) db.session.commit() flash('Food added!') return redirect(url_for('home')) if le_form.exercise.data and le_form.validate_on_submit(): exercise_log = ExerciseLog(amount=le_form.reps.data) exercise_log.user = current_user exercise_log.exercise_id = le_form.exercise.data db.session.add(exercise_log) db.session.commit() flash('Exercise added!') return redirect(url_for('home')) if w_form.weight.data and w_form.validate_on_submit(): weight = Weight(w_form.weight.data) weight.user = current_user db.session.add(weight) db.session.commit() flash('Weight added!') return redirect(url_for('home')) if s_form.steps.data and s_form.validate_on_submit(): steps = Steps(s_form.steps.data) steps.user = current_user db.session.add(steps) db.session.commit() flash('Steps added!') return redirect(url_for('home')) return render_template('home.html', e_form=le_form, f_form=lf_form, s_form=s_form, w_form=w_form, weights=weights, steps=steps, points=points, message=message)
def import_data(): if Path('db/app.db').exists(): click.confirm('app.db already exist, want to remove it?', abort=True) Path('db/app.db').unlink() upgrade() user = create_user() with open("data/steps.csv", 'r') as f: reader = DictReader(f) for line in reader: steps = Steps(steps=line['steps']) steps.date = datetime.fromisoformat(line['datetime']) steps.user = user db.session.add(steps) db.session.commit() with open("data/weights.csv", 'r') as f: reader = DictReader(f) for line in reader: weight = Weight(weight=line['weight']) weight.date = datetime.fromisoformat(line['datetime']) weight.user = user db.session.add(weight) db.session.commit() with open("data/exercises.csv", 'r') as f: reader = DictReader(f) for line in reader: exercise = Exercise(name=line['name'], kcal_per_rep=line['kcal']) db.session.add(exercise) db.session.commit() with open("data/ingredients.csv", 'r') as f: reader = DictReader(f) for line in reader: ingredient = Ingredient(name=line['name'], kcal_per_100_gram=line['kcal']) db.session.add(ingredient) db.session.commit() with open("data/food_log.csv", 'r') as f: reader = DictReader(f) for line in reader: food_log = FoodLog() food_log.user = user food_log.ingredient_id = line['ingredient_id'] food_log.grams = line['grams'] food_log.timestamp = datetime.fromisoformat(line['datetime']) db.session.add(food_log) db.session.commit() with open("data/exercise_log.csv", 'r') as f: reader = DictReader(f) for line in reader: exercise_log = ExerciseLog() exercise_log.user = user exercise_log.exercise_id = line['exercise_id'] exercise_log.amount = line['amount'] food_log.timestamp = datetime.fromisoformat(line['datetime']) db.session.add(exercise_log) db.session.commit()
def weight(self, weight_data): newWeight = Weight(created=weight_data.date.data, weight=weight_data.weight.data, user_id=session['user_id']) db_session.add(newWeight) db_session.commit()
def profile(): if 'email' not in session: return redirect(url_for('index')) groupnameList = [] grouplist = [] user = User.query.filter_by(email = session['email']).first() nickname = user.nickname if user is None: return redirect(url_for('index')) else: groupInfo = Group.query.filter_by(owner=session['email']).all() if groupInfo is not None: for ele in groupInfo: groupnameList.append(ele.groupname) if user.grouplist != "": grouplist = user.grouplist.split(",") number = [""] def makePicture(length): weight = Weight.query.filter_by(email = session['email']).first() if weight is not None: daysFromLast = (datetime.now(pytz.timezone(weight.timezone)).date() - weight.lastupdated).days weightarray = weight.weight.split(",") recordarray = [] day = [] labels = [] reduce = (length / 30) + 1 plt.figure(figsize=(12, 4)) if length - daysFromLast > 1: for i in range(0, daysFromLast): recordarray.append(None) for i in range(0, length - daysFromLast): if len(weightarray) > 0: recordarray.append(float(weightarray.pop())) else: recordarray.append(None) recordarray.reverse() def getfirst(array): for ele in array: if ele != None: return ele def getlast(array): array.reverse() return getfirst(array) number[1] = getfirst(recordarray) number[2] = getlast(recordarray) recordarray.reverse() for i in range(0, length): day.append(i) if reduce == 0 or i%reduce == 0: labels.append(str(datetime.now(pytz.timezone(weight.timezone)).date() - timedelta(i))) labels.reverse() for i in range(0, length): plt.plot(day[i],recordarray[i], linestyle="None",marker = "o", markersize = 8, color = "green") #zhfont1 = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc') plt.plot(day, recordarray, linestyle="solid",color="#2BCE48",linewidth=3,label=unicode(weight.nickname) if i ==0 else "") plt.legend(loc='best',prop=prop) file = "/var/www/weight_overflow/files/static/weightgram/users/" + nickname plt.xticks(day, labels, rotation=45) plt.subplots_adjust(bottom=0.30) if reduce != 0: plt.xticks(np.arange(min(day), max(day)+1, reduce)) if os.path.exists(file): filenumber = int(os.listdir(file)[0].split(".")[0][1:]) filenumber += 1 number[0] = str(filenumber) os.remove(file + "/w" + str(filenumber - 1) + ".png") plt.savefig(file + "/w" + str(filenumber) + ".png") else: os.mkdir(file) plt.savefig(file + "/w0.png") number[0] = "0" plt.clf() return True else: return False return False warn = "" form = EditForm(prefix = "form") form1 = WeightForm(prefix = "form1") form2 = UserProgressForm(prefix = "form2") newuser = False timezoneRecorded = False message = "" weight = Weight.query.filter_by(email = session['email']).first() if weight != None: if len(weight.weight.split(",")) == 1: newuser = True else: newuser = True if user.timezone != None: timezoneRecorded = True if request.method == 'POST': #for weight form if form1.submit.data and form1.validate(): user = Weight.query.filter_by(email = session['email']).first() if user == None: currentUser = User.query.filter_by(email = session['email']).first() grouplist = User.query.filter_by(email = session['email']).first().grouplist newWeight = Weight(session['email'],form1.todaysweight.data,datetime.now(pytz.timezone(currentUser.timezone)).date(),datetime.now(pytz.timezone(currentUser.timezone)).date(),grouplist, nickname, currentUser.timezone, currentUser.target) db.session.add(newWeight) db.session.commit() if user != None: if (datetime.now(pytz.timezone(user.timezone)).date() - user.lastupdated).days == -1: weight = Weight.query.filter_by(email = session['email']).first() if user.begindate == user.lastupdated: weight.begindate = datetime.now(pytz.timezone(user.timezone)).date() weight.weight = form1.todaysweight.data else: temp = weight.weight.split(",") temp[-2] = form1.todaysweight.data temp.pop() weight.weight = ','.join(temp) weight.daysAbsent = weight.daysAbsent - 1 weight.lastupdated = datetime.now(pytz.timezone(user.timezone)).date() db.session.commit() else: #first day recording, if it's not the first day, go to else temp = (datetime.now(pytz.timezone(user.timezone)).date() - user.lastupdated).days if temp > 0: user.daysAbsent = temp if user.daysAbsent == 0: user.weight = "%.2f"%(float(form1.todaysweight.data)) #after first day else: #days that this ppl is not recording the weight info, this will remain the same if #ppl try to modify today's weight. #check if user have already entered today's weight exist = False if user.lastupdated == datetime.now(pytz.timezone(user.timezone)).date(): exist = True else: user.lastupdated = datetime.now(pytz.timezone(user.timezone)).date() #delete data back to last recorded time if exist: temp = user.weight.split(',') for i in range(0,user.daysAbsent): temp.pop() user.weight = ','.join(temp) #add data back to database last = float(user.weight.split(",")[-1]) now = float(form1.todaysweight.data) differenceEachDay = (now - last)/user.daysAbsent for i in range(1,user.daysAbsent): user.weight += "," + "%.2f"%(i * differenceEachDay + last) user.weight += "," + "%.2f"%(float(form1.todaysweight.data)) db.session.commit() #put user's information into achieve table if they achieve their target weight user = Weight.query.filter_by(email = session['email']).first() if user.target is not None: achieved = Achieved.query.filter_by(email = session['email']).first() begin = float(user.weight.split(",")[0]) target = float(user.target) #requirement to be recorded: not in the least, reached the target, loss more than 10% of ur body weight if float(user.weight.split(",")[-1]) <= target and achieved == None and begin - target >= begin * 0.1: grats = Achieved(user.email, user.nickname, user.begindate,user.lastupdated,user.weight.split(",")[0],user.target) db.session.add(grats) db.session.commit() return redirect(url_for('profile')) #for edit form if form.submit.data and form.validate(): weight = Weight.query.filter_by(email = session['email']).first() user = User.query.filter_by(email = session['email']).first() if form.nickname.data != '': if weight is not None: weight.nickname = form.nickname.data user.nickname = form.nickname.data try: float(form.target.data) if weight is not None: weight.target = form.target.data user.target = form.target.data except ValueError: pass if form.timezone.data != "default": user.timezone = form.timezone.data if weight is not None: weight.timezone = form.timezone.data db.session.commit() return redirect(url_for('profile')) #for user process tracking form if form2.submit.data and form2.validate(): number = ["filenumber","startweight","finishweight"] if form2.days.data in ["7","30"]: if makePicture(int(form2.days.data)) == True: loss = number[1] - number[2] if loss < 0: message = "Seriously? are you really try to lose weight?" else: message = "You lose " + "%.2f"%(loss) + " Kg in " + form2.days.data + " days" number = number[0] else: number = [""] warn = "Did you at least record twice during those days?" elif form2.days.data == "max": weight = Weight.query.filter_by(email = session['email']).first() days = (datetime.now(pytz.timezone(weight.timezone)).date() - weight.begindate).days + 1 makePicture(days) loss = number[1] - number[2] if loss < 0: message = "Seriously? are you really try to lose weight?" else: message = "You lose " + "%.2f"%(loss) + " Kg in " + str(len((Weight.query.filter_by(email = session['email']).first()).weight.split(","))) + " days" number = number[0] return render_template('profile.html',nickname = user.nickname,email = user.email,groupnameList = groupnameList, grouplist=grouplist, form = form, form1 = form1, form2 = form2, number = number, newuser = newuser, timezoneRecorded = timezoneRecorded, message = message, warn = warn)