Browse Source

/stats route added

Akash Singh 3 years ago
parent
commit
dac2c0c8e2
3 changed files with 57 additions and 3 deletions
  1. 1 0
      .gitignore
  2. 11 2
      StatisticServer/models.py
  3. 45 1
      StatisticServer/routes.py

+ 1 - 0
.gitignore

@@ -58,3 +58,4 @@ docs/_build/
 # PyBuilder
 target/
 
+/venv/

+ 11 - 2
StatisticServer/models.py

@@ -38,7 +38,13 @@ class TestRunStatistics(db.Model):
 
     def to_json(self):
         dic = self.__dict__
-        return dic
+        new_dic = {}
+        for key in dic:
+            if key[0] == "_":
+                pass
+            else:
+                new_dic[key] = dic[key]
+        return new_dic
 
     def update(self, kwargs):
         for key, value in kwargs.items():
@@ -57,7 +63,10 @@ class ActivityStatistics(db.Model):
 
     def to_json(self):
         dic = self.__dict__
-        return dic
+        new_dic ={}
+        new_dic['TestRunUUID'] = dic['TestRunUUID']
+        new_dic[dic['Key']] = dic['Value']
+        return new_dic
 
     def update(self, kwargs):
         for key, value in kwargs.items():

+ 45 - 1
StatisticServer/routes.py

@@ -1,5 +1,5 @@
 from StatisticServer import app, db
-from flask import request, jsonify, abort, make_response
+from flask import request, jsonify, abort, make_response, Response
 from StatisticServer.models import TestRunStatistics, ActivityStatistics
 from sqlalchemy import exc
 
@@ -19,6 +19,50 @@ def main():
     return jsonify(success=True)
 
 
+@app.route('/stats', methods=['GET'])
+def stats_download(): # Will convert database data in csv and response csv file to request
+    test_stats = db.session.query(TestRunStatistics).all()
+    activities = [] # List to maintain and sync Activity type data with dic
+    dic = {} # Contains header as key and datas inside list
+    first = True # Used in first loop of TestSta
+    for test_stat in test_stats:
+        # Iter through every data in TestRunStatistics the get the data for same UUID from ActivityStatistics
+        activity_stats = db.session.query(ActivityStatistics
+                                          ).filter(ActivityStatistics.TestRunUUID == test_stat.TestRunUUID).all()
+        test_json = test_stat.to_json()
+        for key in test_json:
+            if first:
+                dic[key] = []
+            dic[key].append(test_json[key])
+        first = False
+        for activity_stat in activity_stats:
+            activity_json = activity_stat.to_json()
+            for key in activity_json:
+                if key == "TestRunUUID":
+                    continue
+                elif key not in dic: # As Activities are dynamic we are adding new found activites in header & filling default value 0
+                    dic[key] = []
+                    for x in range(len(dic["TestRunUUID"]) - 1): # Adding 0 values with current header in previous data
+                        dic[key].append(0)
+                    activities.append(key)
+                dic[key].append(activity_json[key])
+        for key in activities: # If all activities we found till now are not present in Current loop then will add them with 0 value
+            while len(dic[key]) < len(dic["TestRunUUID"]):
+                dic[key].append(0)
+    csv = [','.join([key for key in dic])] # header row as string with comma seporator
+    for x in range(len(dic["TestRunUUID"])): # Value rows as string with comma seporator
+        lis = []
+        for key in dic:
+            lis.append(str(dic[key][x]))
+        csv.append(','.join(lis))
+    data = '\n'.join(csv) # Joining all rows in one string with newline between them. This string is treated as csv file while sending data
+    return Response(
+                    data,
+                    mimetype="text/csv",
+                    headers={"Content-disposition":
+                                 "attachment; filename=statistics_database.csv"})
+
+
 def process_data(data):
     dict = {}
     for key in data: