Commit e495b85c authored by Lysander Trischler's avatar Lysander Trischler

Add body weight support

parent b178a216
......@@ -74,10 +74,23 @@ if __name__ == "__main__":
class BaseHandler(tornadyse.RequestHandler):
@property
def db(self):
return self.application.db
def prepare(self):
def format_datetime(datetime):
if "Opera" in self.request.headers.get("User-Agent", ""):
#if datetime.seconds == 0: #or self.current_user.username == "wf":
return datetime.strftime("%Y-%m-%dT%H:%MZ")
#else:
# return datetime.strftime("%Y-%m-%dT%H:%M:%SZ")
return datetime.strftime("%d.%m.%Y %H:%M:%S")
self.format_datetime = format_datetime
def login(self, username, password):
ldap_user = tornadyse.isobeef_ldap_auth(self, username, password)
if ldap_user:
......@@ -110,6 +123,14 @@ if __name__ == "__main__":
return ldap_user
def format_weight(self, grams):
if grams is None:
return ""
if grams < 1000:
return "%d g" % grams
return "%d,%d kg" % divmod(grams, 1000)
def get_template_namespace(self):
namespace = tornadyse.RequestHandler.get_template_namespace(self)
namespace.update({
......@@ -117,7 +138,9 @@ if __name__ == "__main__":
"today": self.today,
"date": date,
"gpx_url": self.gpx_url,
"distance": distance
"distance": distance,
"format_datetime": self.format_datetime,
"format_weight": self.format_weight
})
return namespace
......@@ -261,20 +284,10 @@ if __name__ == "__main__":
@route(r'/exercises/add', aliases=[r'/add'])
class AddExerciseHandler(BaseHandler):
def prepare(self):
def format_datetime(datetime):
if "Opera" in self.request.headers.get("User-Agent", ""):
#if datetime.seconds == 0: #or self.current_user.username == "wf":
return datetime.strftime("%Y-%m-%dT%H:%MZ")
#else:
# return datetime.strftime("%Y-%m-%dT%H:%M:%SZ")
return datetime.strftime("%d.%m.%Y %H:%M:%S")
self.format_datetime = format_datetime
@authenticated
def get(self):
exercise = Exercise(user=self.current_user)
self.render("add.html", exercise=exercise, format_datetime=self.format_datetime)
self.render("add.html", exercise=exercise)
def _parse_datetime(self, text):
if not text:
......@@ -476,7 +489,7 @@ if __name__ == "__main__":
end=end)
if self.get_status() != 200:
self.render("add.html", exercise=exercise, format_datetime=self.format_datetime)
self.render("add.html", exercise=exercise)
else:
exercise_id = self.db.execute_lastrowid("""
INSERT INTO exercises (username, discipline, count, start, end)
......@@ -1010,6 +1023,79 @@ if __name__ == "__main__":
self.set_header("Content-Type", "text/plain; charset=UTF-8")
self.finish("%s h" % self.application.uptime())
def parse_weight(s):
if not s:
raise ValueError("Invalid weight.")
def parse_kg(s):
return int(float(s.replace("kg", "", 1).replace(",", ".", 1)) * 1000)
# remove spaces and parse according given unit or fall back to kg
s = s.replace(" ", "")
if "kg" in s: return parse_kg(s)
if "g" in s: return int(s.replace("g", "", 1))
return parse_kg(s)
@route(r'/weights/add')
class AddWeightHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
self.render("add_weight.html", weight=Weight(user=self.current_user))
@tornado.web.authenticated
def post(self):
grams = self.get_string_argument("weight", None)
try:
grams = parse_weight(grams)
# humans should not weight more than 300kg
if grams > 300000:
self.error_messages.append("Du musst aber fett sein, mein lieber Scholli!")
self.set_status(400)
except ValueError as e:
self.error_messages.append("Fehlerhafte Gewichtsangabe!")
self.set_status(400)
grams = None
date = self.get_string_argument("date", None)
if not date:
self.error_messages.append("Bitte einen gültigen Messzeitpunkt wählen!")
self.set_status(400)
else:
try:
date = tornadyse.dtutils.parse_datetime(date)
except Exception as e:
self.error_messages.append("Fehlerhafte Messzeitpunktangabe: %r" % e)
self.set_status(400)
else:
# date cannot be more than one week
if date > (self.now + datetime.timedelta(days=7)):
self.error_messages.append("Der Messzeitpunkt liegt zu weit in der Zukunft!")
self.set_status(400)
# date cannot be before 1970-01-01 00:00:00
if date < datetime.datetime(year=1970, month=1, day=1):
self.error_messages.append("Der Messzeitpunkt liegt zu weit in der Vergangenheit!")
self.set_status(400)
weight = Weight(user=self.current_user, grams=grams, date=date)
if self.get_status() != 200:
self.render("add_weight.html", weight=weight)
else:
weight_id = self.db.execute_lastrowid("""
INSERT INTO weights (username, grams, date)
VALUES (%s, %s, %s)
""", weight.user.username, weight.grams, weight.date)
self.success_messages.append("Körpergewicht erfolgreich eingetragen!")
self.redirect(self.reverse_url("LoginOrTodayHandler"))
class Exercise(object):
def __init__(self, id=None, username=None, user=None, discipline=None, count=None, start=None, end=None):
self.id = id
......@@ -1041,9 +1127,32 @@ if __name__ == "__main__":
self._end = end
def __repr__(self):
return u"<Exercise id=%s username=%s user=%s discipline=%s count=%s start=%s end=%s" % (
return u"<Exercise id=%s username=%s user=%s discipline=%s count=%s start=%s end=%s>" % (
self.id, self.username, self.user, self.discipline, self.count, self.start, self.end)
class Weight(object):
def __init__(self, id=None, username=None, user=None, grams=None, date=None):
self.id = id
self.username = username
self.user = user
self.grams = grams
self._date = date or datetime.datetime.now()
@property
def date(self):
if self._date.tzinfo is None:
self._date = berlin.localize(self._date)
return self._date
@date.setter
def date(self, date):
self._date = date
def __repr__(self):
return u"<Weight id=%s username=%s user=%s grams=%s date=%s>" % (
self.id, self.username, self.user, self.grams, self.date)
class UserLinkModule(tornado.web.UIModule):
def render(self, user=None, username=None):
if user is not None:
......
{% extends base.html %}
{% block title %}Gewicht eintragen{% end %}
{% block content %}
<section>
<h1>Gewicht eintragen</h1>
<form action="{{ request.uri }}" method="post" enctype="application/x-www-form-urlencoded">
<fieldset>
<legend>Körpergewicht eintragen</legend>
<dl>
<dt><label for=weight>Gewicht in kg</label></dt>
<dd>
<input type=number name=weight id=weight value="{{ format_weight(weight.grams) }}" maxlength=7 min=0 max=9001 placeholder="das Körpergewicht in Kilogramm" />
<p class=info>Körpergewicht in Kilogramm</p>
</dd>
<dt><label for=date>Datum</label></dt>
<dd>
<input type=datetime name=date id=date value="{{ format_datetime(weight.date) }}" maxlength=32 placeholder="Datum und Uhrzeit des Messzeitpunkts" />
<p class=info>Datum und Uhrzeit des Messzeitpunkts, z.B. im Format <code>[TT.[MM.[JJJJ]]] <i>[HH:]MM</i>[:SS]</code></p>
</dd>
</dl>
<p class=buttonbox>
<input type=submit name=add value="Eintragen" />
</p>
</fieldset>
</form>
</section>
{% end %}
......@@ -11,10 +11,10 @@
<h1>{% module navi("LoginOrTodayHandler", "Kraftwerk") %}</h1>
<nav>
{% if current_user %}
{% module navi("LoginOrTodayHandler", "Heute") %}
{% module navi("ListUsersHandler", "Benutzerübersicht") %}
{% module navi("ListExercisesHandler", "Übungsübersicht") %}
{% module navi("AddExerciseHandler", "Übung eintragen") %}
{% module navi("AddWeightHandler", "Gewicht eintragen") %}
{% module navi("ChangeAPIPasswordHandler", "API-Passwort ändern") %}
{% module navi("LogoutHandler", "%s abmelden" % (current_user.display_name or current_user.username)) %}
{% end %}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment