윤영준 윤영준 2024-09-09
rebulding server
@eacbb0f1135304ce641b9570c6d21ac7c863db68
action.py
--- action.py
+++ action.py
@@ -31,9 +31,8 @@
 
 
 @Action.route('/gps_update')
-class fileUpload(Resource):
+class GPS_update(Resource):
     def post(self):
-        db = DB()
         token = request.headers.get('Authorization')
         if not token:
             return jsonify({'result': 'fail', 'msg': '토큰이 없습니다.'})
@@ -42,7 +41,8 @@
             decoded_token = jwt.decode(token, "secret", algorithms=['HS256'])
             #print(decoded_token)
             user_id = decoded_token['id']
-    
+
+        db = DB()
 
         data = request.get_json()
         if len(data["trip_id"]) !=64:
@@ -76,18 +76,32 @@
 
 
 @Action.route('/trip_and_score_update')
-class fileUpload(Resource):
+class TRIP_insert(Resource):
     def post(self):
-        db = DB()
         token = request.headers.get('Authorization')
+
+        # Check if token is provided
         if not token:
-            return jsonify({'result': 'fail', 'msg': '토큰이 없습니다.'})
-        else:
+            return jsonify({'result': 'fail', 'msg': '토큰이 없습니다.'}), 401
+
+        try:
             # Decode the token to verify it
             decoded_token = jwt.decode(token, "secret", algorithms=['HS256'])
-            # print(decoded_token)
             user_id = decoded_token['id']
+        except jwt.ExpiredSignatureError:
+            return jsonify({'result': 'fail', 'msg': '토큰이 만료되었습니다.'}), 401
+        except jwt.InvalidTokenError:
+            return jsonify({'result': 'fail', 'msg': '유효하지 않은 토큰입니다.'}), 401
 
+        # Interact with the DB to get user history
+        try:
+            db = DB()
+            result, status_code = db.get_history(user_name=user_id)
+            return jsonify({'result': 'success', 'data': result}), status_code
+        except Exception as e:
+            return jsonify({'result': 'fail', 'msg': str(e)}), 500
+
+        db = DB()
         data = request.get_json()
         if len(data["trip_id"]) != 64:
             return jsonify({500: "ERROR! INVALID TRIP_ID!"})
@@ -120,4 +134,30 @@
             helmet_on,
             final_score
         )
-        return jsonify({'result': f'success'})
(파일 끝에 줄바꿈 문자 없음)
+        return jsonify({'result': f'success'})
+
+@Action.route('/get_history')
+class Get_history(Resource):
+    def post(self):
+        token = request.headers.get('Authorization')
+
+        # Check if token is provided
+        if not token:
+            return jsonify({'result': 'fail', 'msg': '토큰이 없습니다.'}), 401
+
+        try:
+            # Decode the token to verify it
+            decoded_token = jwt.decode(token, "secret", algorithms=['HS256'])
+            user_id = decoded_token['id']
+        except jwt.ExpiredSignatureError:
+            return jsonify({'result': 'fail', 'msg': '토큰이 만료되었습니다.'}), 401
+        except jwt.InvalidTokenError:
+            return jsonify({'result': 'fail', 'msg': '유효하지 않은 토큰입니다.'}), 401
+
+        # Interact with the DB to get user history
+        try:
+            db = DB()
+            result, status_code = db.get_history(user_name=user_id)
+            return jsonify({'result': 'success', 'data': result}), status_code
+        except Exception as e:
+            return jsonify({'result': 'fail', 'msg': str(e)}), 500
(파일 끝에 줄바꿈 문자 없음)
database/database.py
--- database/database.py
+++ database/database.py
@@ -254,8 +254,79 @@
             abrupt_deceleration_count,
             helmet_on,
             final_score
+            )
         )
-                         )
+
+    def get_history(self, user_name):
+        """
+        Retrieves all trip logs for the specified user within the last month and returns them in JSON format.
+            [
+              {
+                "trip_id": "trip_001",
+                "timestamp": "2024-09-01 12:45:00",
+                "total_distance_m": 1000.5,
+                "total_time_s": 600,
+                "abrupt_start_count": 3,
+                "abrupt_stop_count": 2,
+                "abrupt_acceleration_count": 1,
+                "abrupt_deceleration_count": 1,
+                "helmet_on": true,
+                "final_score": 85.5
+              },
+              {
+                "trip_id": "trip_002",
+                "timestamp": "2024-09-02 14:30:00",
+                "total_distance_m": 1500.0,
+                "total_time_s": 720,
+                "abrupt_start_count": 2,
+                "abrupt_stop_count": 3,
+                "abrupt_acceleration_count": 1,
+                "abrupt_deceleration_count": 2,
+                "helmet_on": false,
+                "final_score": 90.0
+              }
+            ]
+        """
+        try:
+            # Execute the query to retrieve logs within the last month
+            self.cur.execute("""
+                SELECT trip_id, timestamp, total_distance_m, total_time_s, abrupt_start_count, 
+                       abrupt_stop_count, abrupt_acceleration_count, abrupt_deceleration_count, 
+                       helmet_on, final_score
+                FROM trip_log
+                WHERE username = %s
+                AND timestamp >= NOW() - INTERVAL '1 month'
+            """, (user_name,))
+
+            # Fetch all results
+            rows = self.cur.fetchall()
+
+            # Format the results into a list of dictionaries
+            result = []
+            for row in rows:
+                trip_log = {
+                    "trip_id": row[0],
+                    "timestamp": row[1].strftime("%Y-%m-%d %H:%M:%S"),  # Format timestamp
+                    "total_distance_m": row[2],
+                    "total_time_s": row[3],
+                    "abrupt_start_count": row[4],
+                    "abrupt_stop_count": row[5],
+                    "abrupt_acceleration_count": row[6],
+                    "abrupt_deceleration_count": row[7],
+                    "helmet_on": bool(row[8]),  # Convert INT to Boolean
+                    "final_score": row[9]
+                }
+                result.append(trip_log)
+
+            # Convert the result list to JSON format
+            return json.dumps(result), 200
+
+        except psycopg2.Error as e:
+            self.conn.rollback()
+            return {'status': 'error', 'message': str(e)}, 500
+
+
+
 
     def close_connection(self):
         cur = self.cur
Add a comment
List