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,)