윤영준 윤영준 2024-09-09
rebulding server
@73c840a7301e7983fc27bafcfcf42d82c35378c2
action.py
--- action.py
+++ action.py
@@ -17,6 +17,18 @@
     description="노드 분석을 위해 사용하는 api.",
 )
 
+trip_log_model = Action.model('TripLog', {
+    'trip_id': fields.String(required=True, description='The ID of the trip (64 characters)'),
+    'trip_distance_m': fields.Float(required=True, description='Total distance traveled in meters'),
+    'trip_time_s': fields.Float(required=True, description='Total time of the trip in seconds'),
+    'abrupt_start_count': fields.Integer(required=True, description='Count of abrupt starts'),
+    'abrupt_stop_count': fields.Integer(required=True, description='Count of abrupt stops'),
+    'abrupt_acceleration_count': fields.Integer(required=True, description='Count of abrupt accelerations'),
+    'abrupt_deceleration_count': fields.Integer(required=True, description='Count of abrupt decelerations'),
+    'helmet_on': fields.Integer(required=True, description='Whether the helmet was worn during the trip, must be 0 or 1 with 1 is the helmet on.'),
+    'final_score': fields.Float(required=True, description='The final safety score for the trip')
+})
+
 
 @Action.route('/gps_update')
 class fileUpload(Resource):
@@ -61,5 +73,51 @@
         # GPS 데이터베이스에 삽입
         db.insert_gps_data(data_csv_block, columns)
         return jsonify({'result': f'success'})
-            
 
+
+@Action.route('/trip_and_score_update')
+class fileUpload(Resource):
+    def post(self):
+        db = DB()
+        token = request.headers.get('Authorization')
+        if not token:
+            return jsonify({'result': 'fail', 'msg': '토큰이 없습니다.'})
+        else:
+            # Decode the token to verify it
+            decoded_token = jwt.decode(token, "secret", algorithms=['HS256'])
+            # print(decoded_token)
+            user_id = decoded_token['id']
+
+        data = request.get_json()
+        if len(data["trip_id"]) != 64:
+            return jsonify({500: "ERROR! INVALID TRIP_ID!"})
+
+        if len(data["trip_log"]["timestamp"]) == 0:
+            return jsonify({500: "ERROR! 'trip_log' is empty!"})
+
+        trip_id = data["trip_id"]
+        trip_distance_m = data["trip_distance_m"]
+        trip_time_s = data["trip_time_s"]
+        abrupt_start_count = data["abrupt_start_count"]
+        abrupt_stop_count = data["abrupt_stop_count"]
+        abrupt_acceleration_count = data["abrupt_acceleration_count"]
+        abrupt_deceleration_count = data["abrupt_deceleration_count"]
+        helmet_on = data["helmet_on"]
+        final_score = data["final_score"]
+
+        if not (helmet_on == 1) or (helmet_on == 0):
+            return jsonify({500: f"ERROR! INVALID 'helmet_on'! \n helmet_on : {helmet_on}"})
+
+        db.insert_trip_data(
+            user_id,
+            trip_id,
+            trip_distance_m,
+            trip_time_s,
+            abrupt_start_count,
+            abrupt_stop_count,
+            abrupt_acceleration_count,
+            abrupt_deceleration_count,
+            helmet_on,
+            final_score
+        )
+        return jsonify({'result': f'success'})
(파일 끝에 줄바꿈 문자 없음)
auth.py
--- auth.py
+++ auth.py
@@ -6,9 +6,6 @@
 import jwt
 
 
-
-
-
 users = {}
 
 Auth = Namespace(
@@ -161,8 +158,15 @@
         # Call the login_user method from the UserManager instance
         result, status_code = user_manager.login_user(user_data)
 
-        # Return the appropriate response based on the result from UserManager
-        return result, status_code
+        if result['status'] == 'success':
+            payload = {
+                'id': id,
+                'exp': datetime.datetime.utcnow() + datetime.timedelta(days=14)
+            }
+            token = jwt.encode(payload, "secret", algorithm='HS256')
+            return jsonify({'result': 'success', 'token': token})
+        else :
+            return jsonify({'result': 'fail', 'msg': '아이디/비밀번호가 일치하지 않습니다.'})
 
 
 @Auth.route('/secession')
database/database.py
--- database/database.py
+++ database/database.py
@@ -213,7 +213,50 @@
         decrypted_phone = self.decrypt_aes(encrypted_phone, phone_iv)
 
         return {'status': 'success', 'phone_number': decrypted_phone}, 200
-        
+
+    def insert_gps_data(self, csv_block, columns):
+        cur = self.conn.cursor()
+        data = StringIO(csv_block)
+
+        # using COPY instead of INSERT to do even less operation per data.
+        cur.copy_from(data, 'gps_data', sep=',', columns=columns)
+        self.conn.commit()
+        cur.close()
+        return True
+
+    def insert_trip_data(
+            self,
+            username,
+            trip_id,
+            total_distance_m,
+            total_time_s,
+            abrupt_start_count,
+            abrupt_stop_count,
+            abrupt_acceleration_count,
+            abrupt_deceleration_count,
+            helmet_on,
+            final_score
+    ):
+
+        self.cur.execute(f"""
+            INSERT INTO trip_log (username, 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)
+            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+        """, (
+            username,
+            trip_id,
+            datetime.now(),
+            total_distance_m,
+            total_time_s,
+            abrupt_start_count,
+            abrupt_stop_count,
+            abrupt_acceleration_count,
+            abrupt_deceleration_count,
+            helmet_on,
+            final_score
+        )
+                         )
+
     def close_connection(self):
         cur = self.cur
         cur.close()
Add a comment
List