Browse Source

feat: 修复了update用户和垃圾袋时的SQL错误

SongZihuan 3 years ago
parent
commit
1b31b74ba1
11 changed files with 61 additions and 48 deletions
  1. 5 5
      core/garbage.py
  2. 7 7
      core/user.py
  3. 1 1
      equipment/scan.py
  4. 1 1
      equipment/scan_garbage.py
  5. 3 3
      sql/base_db.py
  6. 6 6
      sql/garbage.py
  7. 4 1
      sql/mysql_db.py
  8. 26 19
      tk_ui/station.py
  9. 5 2
      tk_ui/station_event.py
  10. 1 1
      tool/location.py
  11. 2 2
      tool/time_.py

+ 5 - 5
core/garbage.py

@@ -16,7 +16,7 @@ class GarbageType:
 
 class GarbageBag:
     def __init__(self, gid: gid_t):
-        self._gid: gid_t = gid
+        self._gid: gid_t = gid_t(gid)
         self._have_use: bool = False
         self._have_check: bool = False
 
@@ -131,9 +131,9 @@ class GarbageBag:
                 use_time = HGSTime(use_time)
             if not isinstance(location, HGSLocation):
                 location = HGSLocation(location)
-            self._type: enum = garbage_type
+            self._type: enum = enum(garbage_type)
             self._use_time: HGSTime = use_time
-            self._user: uid_t = user
+            self._user: uid_t = uid_t(user)
             self._loc: HGSLocation = location
         finally:
             self._lock.release()
@@ -144,7 +144,7 @@ class GarbageBag:
             assert self._have_use
             assert not self._have_check
             self._have_check = True
-            self._check = use_right
-            self._checker = check_uid
+            self._check = bool(use_right)
+            self._checker = uid_t(check_uid)
         finally:
             self._lock.release()

+ 7 - 7
core/user.py

@@ -19,9 +19,9 @@ class UserType:
 
 class User(metaclass=abc.ABCMeta):
     def __init__(self, name: uname_t, uid: uid_t, user_type: enum):
-        self._name: uname_t = name
-        self._uid: uid_t = uid
-        self._type: enum = user_type
+        self._name: uname_t = uname_t(name)
+        self._uid: uid_t = uid_t(uid)
+        self._type: enum = enum(user_type)
         self._lock = threading.RLock()
 
     def is_manager(self):
@@ -89,9 +89,9 @@ class User(metaclass=abc.ABCMeta):
 class NormalUser(User):
     def __init__(self, name: uname_t, uid: uid_t, reputation: score_t, rubbish: count_t, score: score_t):
         super(NormalUser, self).__init__(name, uid, UserType.normal)
-        self._reputation = reputation
-        self._rubbish = rubbish
-        self._score = score
+        self._reputation = score_t(reputation)
+        self._rubbish = count_t(rubbish)
+        self._score = score_t(score)
 
     def __repr__(self):
         try:
@@ -112,7 +112,7 @@ class NormalUser(User):
         """
         try:
             self._lock.acquire()
-            info =  {
+            info = {
                 "name": str(self._name),
                 "uid": str(self._uid),
                 "manager": '0',

+ 1 - 1
equipment/scan.py

@@ -12,7 +12,7 @@ class HGSCapture:
         args = *args, *conf.capture_arg
         if cv2.CAP_DSHOW not in args:
             args = *args, cv2.CAP_DSHOW
-        self._capture = cv2.VideoCapture(capnum, *args, **kwargs)
+        self._capture = cv2.VideoCapture(int(capnum), *args, **kwargs)
         self._frame = None
         self._lock = threading.RLock()
 

+ 1 - 1
equipment/scan_garbage.py

@@ -7,7 +7,7 @@ from tool.pic import write_text
 import re
 import os.path
 
-qr_user_pattern = re.compile(r'HGSSystem-QR-GARBAGE:([a-z0-9])+-END', re.I)
+qr_user_pattern = re.compile(r'HGSSystem-QR-GARBAGE:([a-z0-9]+)-END', re.I)
 
 
 def scan_gid(code: QRCode) -> gid_t:

+ 3 - 3
sql/base_db.py

@@ -21,9 +21,9 @@ class DBBit:
 class Database(metaclass=abc.ABCMeta):
     @abc.abstractmethod
     def __init__(self, host: str, name: str, passwd: str):
-        self._host = host
-        self._name = name
-        self._passwd = passwd
+        self._host = str(host)
+        self._name = str(name)
+        self._passwd = str(passwd)
 
     @abc.abstractmethod
     def close(self):

+ 6 - 6
sql/garbage.py

@@ -216,7 +216,7 @@ def update_garbage(garbage: GarbageBag, db: DB) -> bool:
     if re is None:
         return False
 
-    if re.is_use() and not garbage.is_use() or re.is_check()[0] and not garbage.is_check():
+    if re.is_use() and not garbage.is_use() or re.is_check()[0] and not garbage.is_check()[0]:
         return False
 
     if not garbage.is_use() and not garbage.is_check()[0]:
@@ -229,21 +229,21 @@ def update_garbage(garbage: GarbageBag, db: DB) -> bool:
         res = db.done(f"UPDATE garbage SET "
                       f"Flat = 2,"
                       f"UserID = '{info['user']}',"
-                      f"UseTime = {time_from_mysql(info['use_time'])},"
+                      f"UseTime = {mysql_time(info['use_time'])},"
                       f"GarbageType = {info['type']},"
                       f"Location = '{info['loc']}',"
                       f"CheckResult = {info['check']},"
-                      f"CheckerID = '{info['checker']}',"
+                      f"CheckerID = '{info['checker']}' "
                       f"WHERE GarbageID = {gid};")
     elif garbage.is_use():
         res = db.done(f"UPDATE garbage SET "
                       f"Flat = 1,"
                       f"UserID = '{info['user']}',"
-                      f"UseTime = {time_from_mysql(info['use_time'])},"
+                      f"UseTime = {mysql_time(info['use_time'])},"
                       f"GarbageType = {info['type']},"
                       f"Location = '{info['loc']}',"
                       f"CheckResult = NULL,"
-                      f"CheckerID = NULL,"
+                      f"CheckerID = NULL "
                       f"WHERE GarbageID = {gid};")
     else:
         res = db.done(f"UPDATE garbage SET "
@@ -253,7 +253,7 @@ def update_garbage(garbage: GarbageBag, db: DB) -> bool:
                       f"GarbageType = NULL,"
                       f"Location = NULL,"
                       f"CheckResult = NULL,"
-                      f"CheckerID = NULL,"
+                      f"CheckerID = NULL "
                       f"WHERE GarbageID = {gid};")
     return res is not None
 

+ 4 - 1
sql/mysql_db.py

@@ -1,5 +1,7 @@
 import pymysql
 import threading
+import traceback
+
 from conf import mysql_url, mysql_name, mysql_passwd
 from .base_db import Database, DBCloseException
 from tool.type_ import *
@@ -9,7 +11,7 @@ class MysqlDB(Database):
     def __init__(self, host: str = mysql_url, name: str = mysql_name, passwd: str = mysql_passwd):
         super(MysqlDB, self).__init__(host, name, passwd)
         try:
-            self._db = pymysql.connect(user=name, password=passwd, host=host, database="hgssystem")
+            self._db = pymysql.connect(user=self._name, password=self._passwd, host=self._host, database="hgssystem")
         except pymysql.err.OperationalError:
             raise
         self._cursor = self._db.cursor()
@@ -56,6 +58,7 @@ class MysqlDB(Database):
             self._cursor.execute(sql)
         except pymysql.MySQLError:
             self._db.rollback()
+            traceback.print_exc()
             return None
         finally:
             self._db.commit()

+ 26 - 19
tk_ui/station.py

@@ -12,7 +12,7 @@ from PIL import Image, ImageTk
 from tool.type_ import *
 from tool.tk import set_tk_disable_from_list, make_font
 
-from core.user import User, UserNotSupportError
+from core.user import User
 from core.garbage import GarbageBag, GarbageType
 
 from sql.db import DB
@@ -88,13 +88,14 @@ class GarbageStationBase(TkEventMain, metaclass=abc.ABCMeta):
         return True
 
     def __check_normal_user(self):
-        if self.check_user() and self._user.is_manager():
-            raise UserNotSupportError
+        if self.check_user() and not self._user.is_manager():
+            return True
+        return False
 
     def __check_manager_user(self):
-        assert self.check_user()
-        if not self._user.is_manager():
-            raise UserNotSupportError
+        if self.check_user() and self._user.is_manager():
+            return True
+        return False
 
     def get_user_info(self):
         assert self.check_user()
@@ -134,21 +135,26 @@ class GarbageStationBase(TkEventMain, metaclass=abc.ABCMeta):
             return -1
         if not self._user.throw_rubbish(garbage, garbage_type, self._loc):
             return -2
-        update_garbage(garbage, self._db)
-        update_user(self._user, self._db)
+        if not update_garbage(garbage, self._db):
+            return -3
+        if not update_user(self._user, self._db):
+            return -3
         return 0
 
     def check_garbage_core(self, garbage: GarbageBag, check_result: bool) -> int:
-        if not self.__check_normal_user():
+        if not self.__check_manager_user():
             return -1
         user = find_user_by_id(garbage.get_user(), self._db)
         if user is None:
             return -2
         if not self._user.check_rubbish(garbage, check_result, user):
             return -3
-        update_garbage(garbage, self._db)
-        update_user(self._user, self._db)
-        update_user(user, self._db)
+        if not update_garbage(garbage, self._db):
+            return -4
+        if not update_user(self._user, self._db):
+            return -4
+        if not update_user(user, self._db):
+            return -4
         return 0
 
     def ranking(self, limit: int = 0, order_by: str = 'DESC') -> list[Tuple[uid_t, uname_t, score_t, score_t]]:
@@ -223,9 +229,9 @@ class GarbageStationBase(TkEventMain, metaclass=abc.ABCMeta):
 
         info = self._garbage.get_info()
         garbage_type = GarbageType.GarbageTypeStrList_ch[int(info['type'])]
-        if self._garbage.is_check():
+        if self._garbage.is_check()[0]:
             time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(info['use_time'])))
-            check = f'Checker is f{info["checker"][0:conf.tk_show_uid_len]}\n'
+            check = f'Checker is {info["checker"][0:conf.tk_show_uid_len]}\n'
             if info["check"] == '1':
                 check += f'检查结果为 投放正确\n'
             else:
@@ -918,9 +924,10 @@ class GarbageStation(GarbageStationBase):
         self._msg_hide['command'] = lambda: self.hide_msg_rank(True)
         self._msg_hide.place(relx=0.42, rely=0.85, relwidth=0.16, relheight=0.09)
 
-    def set_msg_time_now(self, show_time: float = 10.0):
+    def set_msg_time_now(self, show_time: Optional[float] = None):
         self._msg_time = time.time()
-        self._msg_show_time = show_time
+        if show_time is not None:
+            self._msg_show_time = show_time
 
     def set_msg_time_none(self):
         self._msg_time = None
@@ -1143,9 +1150,9 @@ class GarbageStation(GarbageStationBase):
                 uid.set('error')
             else:
                 uid.set(uid_get[0:21])
-            eval_.set('无(管理员)')
-            rubbish.set('无(管理员)')
-            score.set('无(管理员)')
+            eval_.set('管理员')
+            rubbish.set('无')
+            score.set('无')
             self.__switch_to_manager_user()
         else:
             name.set(user_info.get('name'))

+ 5 - 2
tk_ui/station_event.py

@@ -144,7 +144,6 @@ class ThrowGarbageEvent(StationEventBase):
 
     def start(self, garbage: GarbageBag, garbage_type: enum):
         self.thread = TkThreading(self.func, garbage, garbage_type)
-        self.thread.start()
         return self
 
     def is_end(self) -> bool:
@@ -156,8 +155,10 @@ class ThrowGarbageEvent(StationEventBase):
             self.station.show_warning("垃圾投放", "管理员用户不得投放垃圾", show_time=3.0)
         elif res == -2:
             self.station.show_warning("垃圾投放", "垃圾投放失败", show_time=3.0)
+        elif res == -3:
+            self.station.show_warning("垃圾投放", "数据库操作失败", show_time=3.0)
         else:
-            self.station.show_warning("操作成功", "垃圾袋完成投放")
+            self.station.show_msg("操作成功", "垃圾袋完成投放", show_time=3.0)
 
 
 class CheckGarbageEvent(StationEventBase):
@@ -187,5 +188,7 @@ class CheckGarbageEvent(StationEventBase):
             self.station.show_warning("垃圾检测", "垃圾袋还未使用", show_time=3.0)
         elif res == -3:
             self.station.show_warning("垃圾检测", "垃圾检测提结果交失败", show_time=3.0)
+        elif res == -4:
+            self.station.show_warning("垃圾检测", "数据库操作失败", show_time=3.0)
         else:
             self.station.show_msg("垃圾检测", "垃圾检测提结果交成功", show_time=3.0)

+ 1 - 1
tool/location.py

@@ -3,7 +3,7 @@ from .type_ import *
 
 class HGSLocation:
     def __init__(self, location: location_t):
-        self._loc: location_t = location
+        self._loc: location_t = location_t(location)
 
     def get_location(self) -> location_t:
         return self._loc

+ 2 - 2
tool/time_.py

@@ -7,7 +7,7 @@ class HGSTime:
         if second is None:
             self._time: time_t = time_t(time.time())
         else:
-            self._time: time_t = second
+            self._time: time_t = time_t(second)
         self._time_local: time.struct_time = time.localtime(self._time)
 
     def get_time(self) -> time_t:
@@ -24,7 +24,7 @@ def mysql_time(t=None) -> str:
 
 
 def time_from_mysql(t) -> float:
-    t_struct = time.strptime(t, '%Y-%m-%d %H:%M:%S')
+    t_struct = time.strptime(str(t), '%Y-%m-%d %H:%M:%S')
     return time.mktime(t_struct)