瀏覽代碼

重构了Model, 拆分了方法

NandHyf 1 年之前
父節點
當前提交
60e0e60664
共有 6 個文件被更改,包括 243 次插入220 次删除
  1. 10 30
      Controller.py
  2. 21 179
      Stateful.py
  3. 23 11
      dev.toml
  4. 0 0
      kbc_alt.py
  5. 119 0
      kbc_sqlite.py
  6. 70 0
      kbc_toml.py

+ 10 - 30
Controller.py

@@ -1,14 +1,9 @@
-import Alt, Stateful
+import kbc_alt 
+import Stateful
 import datetime
 
 
 class kbc_controller():
-    def get_config():
-        tomls = Stateful.MatchTomlTable("dev.toml", "app_config", "dict")
-        global app_config
-        app_config = tomls["app_config"]
-
-
     def get_help():
         pass
     
@@ -17,14 +12,14 @@ class kbc_controller():
 
 
     # [todo 3]
-    def InUTC(timeZone=0):
+    def InUTC(timeZone:int=0):
         dt_now_UTC0 = str(datetime.datetime.now(datetime.timezone.utc))
         return(dt_now_UTC0)
     
 
     # [todo 2]
     # 前端只检查输入数量正确, 内容正确统一代回后端检查
-    def InputCheck(inputs):
+    def InputHandler():
         pass
 
 
@@ -36,16 +31,6 @@ class kbc_controller():
             
             # [todo 1]
             # Controller.InputCheck(app_commands)
-            if len(app_commands) < 5:
-                # Add CurrentPath && DBType && Path
-                app_commands.append(currentPath)
-                app_commands.append(app_config["dbPath"])
-                app_commands.append(app_config["dbType"])
-
-                Stateful.Handler(app_commands)
-
-            elif len(app_commands) >= 5:
-                print("app_commands >5 error")
 
 
     # [todo 4]
@@ -57,15 +42,12 @@ class kbc_controller():
 
     # [todo 4]
     def start():
-        # 0. init
-        
-        # 1. get config
-        kbc_controller.get_config()
+        pass
 
-        # 2.
-        startState = Stateful.Handler(['/', app_config["dbPath"], app_config["dbType"]])
-        print(startState)
-        kbc_controller.TransitCommand()
+        # 2. Valid DB
+        # startState = Stateful.Translator(['/', app_config["dbPath"], app_config["dbType"]])
+        # print(startState)
+        # kbc_controller.TransitCommand()
 
 
 class View:
@@ -87,6 +69,4 @@ class LLM():
 
 
 if __name__ == "__main__":
-    # Controller.start()
-    kbc_controller.get_config()
-    
+    kbc_controller.start()   

+ 21 - 179
Stateful.py

@@ -1,10 +1,23 @@
 # from Controller import kbc_config
-import Alt
-import tomlkit, sqlite3
+import kbc_alt
+import kbc_toml
+import kbc_sqlite
 
 
-# ----- Operating Cursor -----
-oc = {
+# ------ Basics ------
+def get_app_config(returnDict:bool=True):
+        tomls = kbc_toml.MatchTomlTable("dev.toml", "app_config", "dict")
+        global app_config
+        app_config = tomls["app_config"]
+
+        if returnDict == True:
+            return app_config
+
+
+# ----- Core Function -----
+def Translator():
+    global oc
+    oc = {
     "dt":str, # DBType
     "dp":str, # DBPath
 
@@ -18,181 +31,10 @@ oc = {
     "tp_to":list, # ~ after command parameter "to"
     "tp_attr":str # ~ like "-name" in "edit -name oldName to newName"
     }
-# some thoughts:
-# class oc():
-#   def get_oc(), def move_oc()
-
-
-# ----- Toml Methods -----
-def GetTomlDoc(tomlName:str):
-    try:
-        with open(tomlName, "rb") as t:
-            doc = tomlkit.load(t)
-
-            if doc == {}:
-                input("error 0: could not found correct config file") 
-                exit()
-
-            return doc
-        
-    except FileNotFoundError:
-        input("error 0: could not found correct config file") 
-        exit()
-    
-
-def MatchTomlKey(tomlName:str, key:str, table:str="none") -> str:
-    doc = GetTomlDoc(tomlName)
-
-    if table == "none":
-        return str(doc.item(key))
-    
-    elif table != "none":
-        d = doc.unwrap()
-        return str(d[table][key])
-
-
-# no differernt between ↑ MatchTomlKey() ↑ except receives and returns in list
-def MatchTomlKeys(tomlName:str, keys:list, table:str="none") -> list:
-    doc = GetTomlDoc(tomlName)
-
-    if table == "none":
-        # rl == 'r'eturn 'l'ist
-        rl = []
-
-        for key in keys:
-            try:
-                rl.append(doc.item(key))
-            except:
-                pass
-
-        return rl
-    
-
-    elif table != "none":
-        rl = []
-        d = doc.unwrap()
-
-        for key in keys:
-            try:
-                rl.append(d[table][key])
-            except:
-                pass
-
-        return rl
-    
-
-def MatchTomlTable(tomlName:str, tableName:str, returnType:str="list"):
-    d = GetTomlDoc(tomlName).unwrap()
-
-    if returnType == "list":
-        return list(d.get(tableName).values())
-    
-    elif returnType == "dict":
-        return d
-    
-
-# ----- Sqlite Methods -----
-def Exec_one(dbPath:str, commands:list):
-    con = sqlite3.connect(dbPath)
-    cur = con.cursor()
-
-    cur.execute(commands)
-    con.commit()
-    re = cur.fetchall()
-    cur.close()
-    con.close()
-
-    return re
-
-
-def IsExist(dbPath:str, tableName:str, itemName:str, returnBool:bool=True):
-    # [todo 4] 这里面的.capitalize()后面需要根据config.toml里面的内容判断
-    # 可能也不用, 因为KBCLEV的表名和本身并无关系
-    tableName = tableName.capitalize()
-
-    sqls = "SELECT name FROM {table} WHERE name='{name}'".format(table=tableName, name=itemName)
-    ie = Exec_one(dbPath, sqls)
-
-    if ie != [] and returnBool == False:
-        return ie
-    
-    elif ie != [] and returnBool == True:
-        return True
-
-    elif ie == []:
-        return False
-    
-    else:
-        # Alt.Err(errCode)
-        print("err <Code>: unexpected error in existence check")
-
-
-# ----- Record_main(DB record as a class) -----
-class RM():
-    def __init__(self, type:str="", name:str="", dscrp:str="", creator:str="", relatedBoard:str="", relatedClass:str="", status:int=10) -> None:
-        self.id = "null"
-        self.type = type
-        self.name = name
-        self.dscrp = dscrp
-        self.creator = creator
-        self.createdTime = "datetime('now')"
-        self.relatedBoard = relatedBoard
-        self.relatedClass = relatedClass
-        self.status = status
-
-    
-    def select(self, selectColumn:str="name", aliveOnly:bool=True):
-        if aliveOnly == True:
-            sqls = "SELECT {sc} FROM compact_main WHERE type='{s.type}' AND name='{s.name}' AND realatedBoard='{s.relatedBoard}' AND relatedClass='{s.relatedClass}' AND status={s.status};".format(sc=selectColumn, s=self)
-        elif aliveOnly == False:
-            sqls = "SELECT {sc} FROM compact_main WHERE type='{s.type}' AND name='{s.name}' AND realatedBoard='{s.relatedBoard}' AND relatedClass='{s.relatedClass}';".format(sc=selectColumn, s=self)
-        
-        return sqls
-
-
-    def add(self):
-        sqls = "INSERT INTO compact_main VALUES({a.id}, '{a.type}', '{a.name}', '{a.dscrp}', '{a.creator}', '{a.createdTime}', '{a.relatedBoard}', '{a.relatedClass}', {a.status});".format(a=self)
-
-        return sqls
-
-
-    def delete(self): # 1. withStatus:int=10? 2. withStatement >= or > or <?
-        sqls = "UPDATE compact_main SET status=-10 WHERE type='{d.type}' AND name='{d.name}' AND relatedBoard='{d.relatedBoard}' AND relatedClass='{d.relatedClass}';".format(d=self)
-
-        return sqls
-
-
-    def edit(self):
-        pass
-
-    def move(self):
-        pass
-
-    def back(self):
-        pass
-
-    def export():
-        pass
-
-
-# ----- Record_log_action(DB record as a class) -----
-class RLA():
-    pass
-
-
-def GenModel():
-    # model IE?
-    # over write?
-    # exec
-    pass
-
-
-# ----- Interactions Handler(with other .py) -----
-def Handler():
-    pass
+    # some thoughts:
+    # class oc():
+    #   def get_oc(), def move_oc()
 
 
 if __name__ == "__main__":
-    asd = RM("board", "KB", "", "n.HE", "", "", )
-    print(asd.select())
-    input("hold: ")
+    pass

+ 23 - 11
dev.toml

@@ -1,6 +1,8 @@
 # ----- DB Configuration -----
 # Just a better reference for dev.db, no functional use(yet)
-[compact_main]
+# ↓ DB name("dev".db)
+#         ↓ Table name
+[dev.compact_main]
 c1_pk = "id INTEGER PRIMARY KEY ASC"
 c2 = "type"
 c3 = "name"
@@ -9,16 +11,16 @@ c5 = "creator"
 c6 = "createdTime"
 c7 = "relatedBoard"
 c8 = "relatedClass"
-c9 = "status"
+c9 = "state"
 
-[log_action]
+[dev.log_action]
 c1_pk = "id INTEGER PRIMARY KEY ASC"
 c2 = "uid" # UNIQUE
 c3 = "commitTime"
 c4 = "type"
 c5 = "commitedAction"
 c6 = "operator"
-c7 = "state"
+c7 = "status"
 
 
 # ----- App Configuration -----
@@ -36,13 +38,11 @@ Start_as_LLM_server = false
 
 
 # ----- Some Notes -----
-# compact_main.status:
+# compact_main.state:
 #   10 = alive
 #   -10 = deleted
 
-# log_action.state:
-#   10 = successfully committed
-#   -10 = committed failed
+# log_action.status:
 
 
 # Set integer prime key: <columnName> INTEGER PRIMARY KEY ASC
@@ -52,19 +52,31 @@ Start_as_LLM_server = false
 
 
 # ----- used sqls -----
-# CREATE TABLE "main" (
+# CREATE TABLE "compact_main" (
 # 	"id"	INTEGER NOT NULL,
-# 	"type"	TEXT NOT NULL,
+# 	"type"	INTEGER NOT NULL,
 # 	"name"	TEXT NOT NULL,
 # 	"dscrp"	TEXT NOT NULL,
 # 	"creator"	TEXT NOT NULL,
 # 	"createdTime"	TEXT NOT NULL,
 # 	"relatedBoard"	TEXT NOT NULL,
 # 	"relatedClass"	TEXT NOT NULL,
-# 	"alive"	INTEGER NOT NULL,
+# 	"state"	INTEGER NOT NULL,
 # 	PRIMARY KEY("id" AUTOINCREMENT)
 # );
 
+# CREATE TABLE "log_action" (
+# 	"id"	INTEGER NOT NULL,
+# 	"uid"	TEXT NOT NULL,
+# 	"commitTime"	TEXT NOT NULL,
+# 	"type"	TEXT NOT NULL,
+# 	"action"	TEXT NOT NULL,
+# 	"operator"	TEXT NOT NULL,
+# 	"status"	TEXT NOT NULL,
+# 	PRIMARY KEY("id" AUTOINCREMENT)
+# );
+
+
 # INSERT INTO compact_main VALUES(null, 'class', 'CL1', 'dscrp', 'n.HE', datetime('now'), 'KB1, KB2', '', 'alive');
 
 # SELECT name FROM compact_main WHERE belongBoard like '%KB1%'

+ 0 - 0
Alt.py → kbc_alt.py


+ 119 - 0
kbc_sqlite.py

@@ -0,0 +1,119 @@
+import sqlite3
+
+
+# ----- Sqlite Methods -----
+def exec_one(dbPath:str, commands:list, fetchall:bool=False):
+    con = sqlite3.connect(dbPath)
+    cur = con.cursor()
+
+    cur.execute(commands)
+    con.commit()
+
+    # if fetchall == input, return 0?
+    if fetchall == True:
+        re = cur.fetchall()
+        return re
+    
+    cur.close()
+    con.close()
+
+    return 0
+
+
+def isExist(dbPath:str, tableName:str, capitalize:bool=False, itemName:str="", returnBool:bool=True):
+    # [todo 4] 这里面.capitalize()后面需要根据config.toml里面的内容判断
+    # 可能也不用, 因为KBCLEV的表名和本身并无关系
+    if capitalize == True:
+        tableName = tableName.capitalize()
+
+    sqls = "SELECT name FROM {table} WHERE name='{name}'".format(table=tableName, name=itemName)
+    ie = Exec_one(dbPath, sqls)
+
+    if ie != [] and returnBool == False:
+        return ie
+    
+    elif ie != [] and returnBool == True:
+        return True
+
+    elif ie == []:
+        return False
+    
+    else:
+        # Alt.Err(errCode)
+        print("err <Code>: unexpected error in existence check")
+
+
+# ----- Record_main(DB record as a class) -----
+class RM():
+    def __init__(self, type:str="", name:str="", dscrp:str="", creator:str="", relatedBoard:str="", relatedClass:str="", state:int=-10) -> None:
+        self.id = "null"
+        self.type = type
+        self.name = name
+        self.dscrp = dscrp
+        self.creator = creator
+        self.createdTime = "datetime('now')"
+        self.relatedBoard = relatedBoard
+        self.relatedClass = relatedClass
+        self.state = state
+
+    
+    def select(self, selectColumn:str="name"):
+        sqls = "SELECT {sc} FROM compact_main WHERE type='{s.type}' AND name='{s.name}' AND realatedBoard='{s.relatedBoard}' AND relatedClass='{s.relatedClass}' AND state={s.state};".format(sc=selectColumn, s=self)                                              
+        
+        return sqls
+    
+
+    def add(self):
+        sqls = "INSERT INTO compact_main VALUES({a.id}, '{a.type}', '{a.name}', '{a.dscrp}', '{a.creator}', '{a.createdTime}', '{a.relatedBoard}', '{a.relatedClass}', {a.state});".format(a=self)
+
+        return sqls
+
+
+    def delete(self): # 1. withstate:int=10? 2. withStatement >= or > or <?
+        sqls = "UPDATE compact_main SET state=-10 WHERE type='{d.type}' AND name='{d.name}' AND relatedBoard='{d.relatedBoard}' AND relatedClass='{d.relatedClass}' AND state=10;".format(d=self)
+
+        return sqls
+
+
+    def edit(self, editColumn:str="", editValue:str=""):
+        sqls = "UPDATE compact_main SET {ec}='{ev}' WHERE type='{e.type}' AND name='{e.name}' AND relatedBoard='{e.relatedBoard}' AND relatedClass='{e.relatedClass}' AND state={e.state};".format(ec=editColumn, ev=editValue, e=self)
+
+        return sqls
+    
+
+    def edit_state(self, editColumn:str="", editValue:int=-10):
+        sqls = "UPDATE compact_main SET {ec}='{ev}' WHERE type='{e.type}' AND name='{e.name}' AND relatedBoard='{e.relatedBoard}' AND relatedClass='{e.relatedClass}' AND state={e.state};".format(ec=editColumn, ev=editValue, e=self)
+
+        return sqls
+
+
+    def move(self, moveColumn:str="", moveValue:str=""):
+        sqls = "UPDATE compact_main SET {mc}='{mv}' WHERE type='{m.type}' AND name='{m.name}' AND relatedBoard='{m.relatedBoard}' AND relatedClass='{m.relatedClass}' AND state=10;".format(mc=moveColumn, mv=moveValue, m=self)
+        
+        return sqls
+
+
+    def back(self, selectColumn:str="name"):
+        sqls = "SELECT {sc} FROM compact_main WHERE type='{s.type}' AND name='{s.name}' AND realatedBoard='{s.relatedBoard}' AND relatedClass='{s.relatedClass}' AND state={s.state};".format(sc=selectColumn, s=self)                                              
+        
+        return sqls
+
+
+    def export(self, selectColumn:str="name"):
+        sqls = "SELECT {sc} FROM compact_main WHERE type='{s.type}' AND name='{s.name}' AND realatedBoard='{s.relatedBoard}' AND relatedClass='{s.relatedClass}' AND state={s.state};".format(sc=selectColumn, s=self)                                              
+        
+        return sqls
+
+
+# ----- Record_log_action(DB record as a class) -----
+class RLA():
+    pass
+
+
+# ----- Auto generate DB from config.toml -----
+def genDB():
+    # model IE?
+    # over write?
+    # exec
+    pass
+

+ 70 - 0
kbc_toml.py

@@ -0,0 +1,70 @@
+import tomlkit
+
+
+# ----- Toml Methods -----
+def GetTomlDoc(tomlName:str):
+    try:
+        with open(tomlName, "rb") as t:
+            doc = tomlkit.load(t)
+
+            if doc == {}:
+                input("error 0: could not found correct config file") 
+                exit()
+
+            return doc
+        
+    except FileNotFoundError:
+        input("error 0: could not found correct config file") 
+        # sec_respond?
+        exit()
+    
+
+def MatchTomlKey(tomlName:str, key:str, table:str="none") -> str:
+    doc = GetTomlDoc(tomlName)
+
+    if table == "none":
+        return str(doc.item(key))
+    
+    elif table != "none":
+        d = doc.unwrap()
+        return str(d[table][key])
+
+
+# no differernt between ↑ MatchTomlKey() ↑ except receives and returns in list
+def MatchTomlKeys(tomlName:str, keys:list, table:str="none") -> list:
+    doc = GetTomlDoc(tomlName)
+
+    if table == "none":
+        # rl == 'r'eturn 'l'ist
+        rl = []
+
+        for key in keys:
+            try:
+                rl.append(doc.item(key))
+            except:
+                pass
+
+        return rl
+    
+
+    elif table != "none":
+        rl = []
+        d = doc.unwrap()
+
+        for key in keys:
+            try:
+                rl.append(d[table][key])
+            except:
+                pass
+
+        return rl
+    
+
+def MatchTomlTable(tomlName:str, tableName:str, returnType:str="list"):
+    d = GetTomlDoc(tomlName).unwrap()
+
+    if returnType == "list":
+        return list(d.get(tableName).values())
+    
+    elif returnType == "dict":
+        return d