[chronojump-server] Results now is being shown with Datatables - Results are refreshed each 5 seconds



commit ec36c29c2f7221e921015dc3adc6d1d4f4625b3a
Author: Marcos Venteo García <mventeo gmail com>
Date:   Tue May 23 20:38:04 2017 +0200

    Results now is being shown with Datatables
    - Results are refreshed each 5 seconds

 chronojump-flask/chronojump_server.py   |  157 +++++++++++++++++++------------
 chronojump-flask/templates/results.html |   70 ++++++++------
 2 files changed, 138 insertions(+), 89 deletions(-)
---
diff --git a/chronojump-flask/chronojump_server.py b/chronojump-flask/chronojump_server.py
index 6630347..c8dc529 100644
--- a/chronojump-flask/chronojump_server.py
+++ b/chronojump-flask/chronojump_server.py
@@ -1,4 +1,5 @@
 from flask import Flask, render_template, request, jsonify, url_for
+from flask_restful import Resource, Api
 from flaskext.mysql import MySQL
 import subprocess
 import os
@@ -10,31 +11,33 @@ config.read('/etc/chronojump.conf')
 
 mysql = MySQL()
 app = Flask(__name__)
-app.config['MYSQL_DATABASE_USER'] = config.get("db","user")
-app.config['MYSQL_DATABASE_PASSWORD'] = config.get("db","password")
-app.config['MYSQL_DATABASE_DB'] = config.get("db","name")
-app.config['MYSQL_DATABASE_HOST'] = config.get("db","server")
+api = Api(app)
+app.config['MYSQL_DATABASE_USER'] = config.get("db", "user")
+app.config['MYSQL_DATABASE_PASSWORD'] = config.get("db", "password")
+app.config['MYSQL_DATABASE_DB'] = config.get("db", "name")
+app.config['MYSQL_DATABASE_HOST'] = config.get("db", "server")
 app.config['CLUB_NAME'] = config.get("club", "name")
 
 mysql.init_app(app)
 
 
 def getHeader(pageTitle):
-    headerPre="<div id=\"textbox\"><p class=\"topalignleft\"><b>"
-    headerPost="</b></p><p class=\"topalignright\"><a href=\"/\">Inici</a></p></div><div style=\"clear: 
both;\"></div>"
+    headerPre = "<div id=\"textbox\"><p class=\"topalignleft\"><b>"
+    headerPost = "</b></p><p class=\"topalignright\"><a href=\"/\">Inici</a></p></div><div style=\"clear: 
both;\"></div>"
     return headerPre + pageTitle + headerPost
 
+
 @app.route('/')
 def main():
     return render_template('index.html',
                            club_name=app.config['CLUB_NAME'])
 
 
-#call:
-#http://192.168.200.1:5000/results
+# call:
+# http://192.168.200.1:5000/results
 @app.route("/results")
 def Results():
-    date = request.args.get('date') #days
+    date = request.args.get('date')  # days
     personId = request.args.get('pId')
     stationId = request.args.get('sId')
     cursor = mysql.connect().cursor()
@@ -57,49 +60,52 @@ def Results():
     bySpeed = True
     repetitonString = ""
     if bySpeed:
-        repString = "lossBySpeed, numBySpeed, rangeBySpeed, vmeanBySpeed, vmaxBySpeed, pmeanBySpeed, 
pmaxBySpeed";
+        repString = "lossBySpeed, numBySpeed, rangeBySpeed, vmeanBySpeed, vmaxBySpeed, pmeanBySpeed, 
pmaxBySpeed"
     else:
-        repString = "lossByPower, numBySpeed, rangeByPower, vmeanByPower, vmaxByPower, pmeanByPower, 
pmaxByPower";
+        repString = "lossByPower, numBySpeed, rangeByPower, vmeanByPower, vmaxByPower, pmeanByPower, 
pmaxByPower"
 
     cursor.execute("SELECT results.dt, person.name, station.name, " +
-            " results.exerciseName, results.resistance, results.repetitions, " + repString + ", comments" +
-            " FROM results, person, station " +
-            " WHERE results.personId = person.id " +
-            " AND results.stationId = station.id " +
-            personStr + dateStr + stationStr +
-            " ORDER by results.id DESC")
+                   " results.exerciseName, results.resistance, results.repetitions, " + repString + ", 
comments" +
+                   " FROM results, person, station " +
+                   " WHERE results.personId = person.id " +
+                   " AND results.stationId = station.id " +
+                   personStr + dateStr + stationStr +
+                   " ORDER by results.id DESC")
     results = cursor.fetchall()
 
     cursor.execute("SELECT results.personId, person.name FROM results, " +
-            "person WHERE results.personId = person.id GROUP BY person.id")
+                   "person WHERE results.personId = person.id GROUP BY person.id")
     persons = cursor.fetchall()
 
     cursor.execute("SELECT * FROM station")
     stations = cursor.fetchall()
 
-    return render_template('results.html', header=getHeader("Resultats"), date=date, pId=personId, 
sId=stationId, bySpeed = bySpeed, results=results, persons=persons, stations=stations)
+    return render_template('results.html', header=getHeader("Resultats"), date=date, pId=personId, 
sId=stationId, bySpeed=bySpeed, results=results, persons=persons, stations=stations)
+
 
-@app.route('/player_list',methods = ['POST', 'GET'])
+@app.route('/player_list', methods=['POST', 'GET'])
 def list():
     cursor = mysql.connect().cursor()
 
-    cursor.execute("SELECT person.*, task.id, task.comment FROM person LEFT JOIN task ON 
task.personId=person.id")
+    cursor.execute(
+        "SELECT person.*, task.id, task.comment FROM person LEFT JOIN task ON task.personId=person.id")
 
     rows = cursor.fetchall()
-    return render_template("player_list.html", header = getHeader("Llistat de jugadors"), rows = rows)
+    return render_template("player_list.html", header=getHeader("Llistat de jugadors"), rows=rows)
 
 
 @app.route('/player_add')
 def player_add():
-        name = request.args.get('name')
-        weight = request.args.get('weight')
-        height = request.args.get('height')
-        rfid = request.args.get('rfid')
+    name = request.args.get('name')
+    weight = request.args.get('weight')
+    height = request.args.get('height')
+    rfid = request.args.get('rfid')
 
-        return render_template('player_add.html', header = getHeader("Afegir jugador"),
-                name=name, weight=weight, height=height, rfid=rfid)
+    return render_template('player_add.html', header=getHeader("Afegir jugador"),
+                           name=name, weight=weight, height=height, rfid=rfid)
 
-@app.route('/player_add_submit',methods = ['POST', 'GET'])
+
+@app.route('/player_add_submit', methods=['POST', 'GET'])
 def player_add_submit():
     if request.method == 'POST':
         msg = ""
@@ -108,7 +114,7 @@ def player_add_submit():
         weight = request.form['weight']
         height = request.form['height']
 
-        #1 check if name is null
+        # 1 check if name is null
         if name is None or name == "":
             msg += " [Falta el nom del jugador] "
         if weight is None or weight == "" or weight == 0:
@@ -116,83 +122,116 @@ def player_add_submit():
         if height is None or height == "" or height == 0:
             msg += " [Falta altura] "
         if msg != "":
-            return render_template("player_add_result.html", header = getHeader("Afegir jugador"),
-                    added=False, msg = msg, name=name, weight=weight, height=height, rfid="")
+            return render_template("player_add_result.html", header=getHeader("Afegir jugador"),
+                                   added=False, msg=msg, name=name, weight=weight, height=height, rfid="")
 
         db = mysql.connect()
         cursor = db.cursor()
 
-        #2 check if person exists
+        # 2 check if person exists
         cursor.execute("SELECT * FROM person WHERE name = '" + name + "'")
         rows = cursor.fetchall()
         if rows:
             msg = "Error, ja existeix el jugador: " + name
-            return render_template("player_add_result.html", header = getHeader("Afegir jugador"),
-                    added=False, msg = msg, name=name, weight=weight, height=height, rfid="")
-
+            return render_template("player_add_result.html", header=getHeader("Afegir jugador"),
+                                   added=False, msg=msg, name=name, weight=weight, height=height, rfid="")
 
-        #3 read RFID
+        # 3 read RFID
         rfidFile = '/tmp/chronojump_rfid.txt'
 
         if os.access(rfidFile, os.W_OK):
             os.remove(rfidFile)
 
-        rfidReadedStatus = subprocess.call("mono /srv/api-app/chronojump-flask/rfid-csharp/RFID.exe", 
shell=True)
+        rfidReadedStatus = subprocess.call(
+            "mono /srv/api-app/chronojump-flask/rfid-csharp/RFID.exe", shell=True)
 
         try:
             with open(rfidFile) as f:
                 rfid = f.read()
         except:
-                rfid = ""
+            rfid = ""
 
         if rfid == "":
-            return render_template("player_add_result.html", header = getHeader("Afegir jugador"),
-                    added=False, msg = "No s'ha detectat el RFID", name=name, weight=weight, height=height, 
rfid=rfid)
+            return render_template("player_add_result.html", header=getHeader("Afegir jugador"),
+                                   added=False, msg="No s'ha detectat el RFID", name=name, weight=weight, 
height=height, rfid=rfid)
 
-
-        #4 check if RFID exists
+        # 4 check if RFID exists
         cursor.execute("SELECT * FROM person WHERE rfid = '" + rfid + "'")
         rows = cursor.fetchall()
         if rows:
             msg = "Error, ja existeix el rfid: " + rfid
-            return render_template("player_add_result.html", header = getHeader("Afegir jugador"),
-                    added=False, msg = msg, name=name, weight=weight, height=height, rfid=rfid)
+            return render_template("player_add_result.html", header=getHeader("Afegir jugador"),
+                                   added=False, msg=msg, name=name, weight=weight, height=height, rfid=rfid)
 
-        #5 insert person and show success
+        # 5 insert person and show success
         cursor.execute("INSERT INTO person (name, weight, height, rfid, imageName) VALUES (" +
-                "'" + name + "', " + str(weight) + ", " + str(height) + ", '" + rfid + "', '')")
+                       "'" + name + "', " + str(weight) + ", " + str(height) + ", '" + rfid + "', '')")
         db.commit()
 
         msg = "Afegit " + name
 
-        return render_template("player_add_result.html", header = getHeader("Afegir jugador"),
-                added=True, image=False, msg = msg, name=name, weight=weight, height=height, rfid=rfid, 
personId=cursor.lastrowid)
+        return render_template("player_add_result.html", header=getHeader("Afegir jugador"),
+                               added=True, image=False, msg=msg, name=name, weight=weight, height=height, 
rfid=rfid, personId=cursor.lastrowid)
+
 
 app.config['UPLOAD_FOLDER'] = "static/images"
 
-@app.route('/uploader', methods = ['GET', 'POST'])
+
+@app.route('/uploader', methods=['GET', 'POST'])
 def uploader():
     if request.method == 'POST':
-        #copy file
+        # copy file
         f = request.files['file']
-        f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
+        f.save(os.path.join(
+            app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
 
-        #update SQL record
+        # update SQL record
         personId = request.form['personId']
         returnToPage = request.form['returnToPage']
 
         db = mysql.connect()
         cursor = db.cursor()
-        cursor.execute("UPDATE person SET imageName = '" + secure_filename(f.filename) + "' WHERE id = " + 
personId)
+        cursor.execute("UPDATE person SET imageName = '" +
+                       secure_filename(f.filename) + "' WHERE id = " + personId)
         db.commit()
 
         if returnToPage == "playerAdd":
-            return render_template("player_add_result.html", header = getHeader("Afegida imatge"),
-                    added=True, image=True, msg = "")
-        else: #playerList
-            cursor.execute("SELECT person.*, task.id, task.comment FROM person LEFT JOIN task ON 
task.personId=person.id")
+            return render_template("player_add_result.html", header=getHeader("Afegida imatge"),
+                                   added=True, image=True, msg="")
+        else:  # playerList
+            cursor.execute(
+                "SELECT person.*, task.id, task.comment FROM person LEFT JOIN task ON 
task.personId=person.id")
             rows = cursor.fetchall()
-            return render_template("player_list.html", header = getHeader("Llistat de jugadors"), rows = 
rows)
+            return render_template("player_list.html", header=getHeader("Llistat de jugadors"), rows=rows)
+
+
+def get_all_results():
+    """Query to get all the results to serve via ajax."""
+    sql = "select results.dt, person.name, station.name, " \
+          " results.exerciseName, results.resistance, results.repetitions, " \
+          "lossBySpeed, numBySpeed, rangeBySpeed, vmeanBySpeed, " \
+          "vmaxBySpeed, pmeanBySpeed, pmaxBySpeed, comments " \
+          "FROM results, person, station where person.id = results.personId and " \
+          "station.id = results.stationId "
+    print sql
+    db = mysql.connect()
+    cursor = db.cursor()
+    cursor.execute(sql)
+    results = cursor.fetchall()
+
+    return results
+
+
+class ResultsAPI(Resource):
+    """Results resource."""
+
+    def get(self):
+        results = get_all_results()
+        return jsonify(data=results)
+
+
+api.add_resource(ResultsAPI, '/api/v1/results')
+
 
 if __name__ == "__main__":
     app.run(host="0.0.0.0", debug=True)
diff --git a/chronojump-flask/templates/results.html b/chronojump-flask/templates/results.html
index 5c02c0c..83e4996 100644
--- a/chronojump-flask/templates/results.html
+++ b/chronojump-flask/templates/results.html
@@ -8,7 +8,7 @@
 <script src="{{ url_for('static', filename='DataTables/media/js/jquery.dataTables.min.js') }}"></script>
 <script src="{{ url_for('static', filename='DataTables/media/js/dataTables.bootstrap.min.js') }}"></script>
 <script type="text/javascript">
-       /*$(document).ready(function() {
+       $(document).ready(function() {
                // Initialize datatable with results
                var table = $('#results').DataTable({
                        "ajax" : "/api/v1/results",
@@ -30,11 +30,44 @@
             }
                });
 
-       });*/
+               setInterval( function () {
+                       table.ajax.reload( null, false );
+               }, 5000 );
+
+       });
 </script>
 {% endblock %}
 
 {% block main_content %}
+       <div class="row">
+
+       </div>
+
+       <table id="results" class="table table-hovered " cellspacing="0" width="100%">
+               <thead>
+                       <th>Data</th>
+                       <th>Jugador</th>
+                       <th>Estació</th>
+                       <th>Exercici</th>
+                       <th>Càrrega</th>
+                       <th>n</th>
+                       <th>Pèrdua</th>
+                       <th>[&nbsp;rep</th>
+                       <th>rang</th>
+                       <th>Vm</th>
+                       <th>VM</th>
+                       <th>Pm</th>
+                       <th>PM&nbsp;]</th>
+                       </thead>
+               </table>
+
+       </div>
+
+{% endblock %}
+
+
+
+<!--
                {% if (not date or date == "") %}
                {% set date = "1" %}
                {% endif %}
@@ -64,7 +97,7 @@
 
                                Data:
 
-                               <span class="noselect"> <!-- make values not selectable (highlight by cursor) 
-->
+                               <span class="noselect">
                                        {% if date == "1" %}
                                        <input type="radio" id="date1" name="date" value="1" 
checked="checked">
                                        {% else %}
@@ -101,7 +134,7 @@
                                        <label for="dateAny">Sempre</label>
                                </span>
 
-                               &nbsp;&nbsp;&nbsp;<!-- Jugador: -->
+                               &nbsp;&nbsp;&nbsp;
 
                                <span class="styled-select slate">
                                        <select name="pId">
@@ -121,7 +154,7 @@
                                        </select>
                                </span>
 
-                               &nbsp;&nbsp;&nbsp;<!-- Estació: -->
+                               &nbsp;&nbsp;&nbsp;
 
                                <span class="styled-select slate">
                                        <select name="sId">
@@ -146,7 +179,7 @@
                        <div style="clear: both;"></div>
                </form>
 
-               <!-- https://www.smashingmagazine.com/2008/08/top-10-css-table-designs/#7-newspaper -->
+
                <table class="table">
                        <thead>
                                <th>Data</th>
@@ -166,7 +199,6 @@
                                <th>VM</th>
                                <th>Pm</th>
                                <th>PM&nbsp;]</th>
-                               <!--<th>Comentaris</th>-->
                        </thead>
 
                        {% for row in results %}
@@ -188,29 +220,7 @@
                                <td>{{row[10]}}</td>
                                <td>{{row[11]}}</td>
                                <td>{{row[12]}}</td>
-                               <!--<td>{{row[13]}}</td>-->
                        </tr>
                        {% endfor %}
                </table>
-
-               <!--<table id="results" class="table table-hovered" cellspacing="0" width="100%">
-                       <thead>
-                               <th>Data</th>
-                               <th>Jugador</th>
-                               <th>Estació</th>
-                               <th>Exercici</th>
-                               <th>Càrrega</th>
-                               <th>n</th>
-                               <th>Pèrdua</th>
-                               <th>[&nbsp;rep</th>
-                               <th>rang</th>
-                               <th>Vm</th>
-                               <th>VM</th>
-                               <th>Pm</th>
-                               <th>PM&nbsp;]</th>
-                               </thead>
-                       </table>
-                       -->
-               </div>
-
-{% endblock %}
+-->


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]