Code refactoring
This commit is contained in:
parent
bf02a7f567
commit
2c34632dd1
104
dm.py
104
dm.py
|
@ -1,5 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
import json, os, configparser, shutil
|
||||
import json, os, configparser, shutil, re
|
||||
from datetime import datetime, date, time
|
||||
|
||||
def firstInit():
|
||||
# Инициализация переменныхб создание конфигруационного файла, копирование шаблонов
|
||||
|
@ -83,6 +84,7 @@ def dbConnect():
|
|||
exit()
|
||||
#print(conn)
|
||||
c = conn.cursor()
|
||||
|
||||
return c
|
||||
|
||||
def createTables(tbl_list):
|
||||
|
@ -118,8 +120,9 @@ def createTables(tbl_list):
|
|||
tbl_list[i]["fieldList"][x]["fType"] + auto_increment
|
||||
if tbl_list[i]["fieldList"][x]["index"] == "PRIMARY KEY":
|
||||
index = "PRIMARY KEY(" + tbl_list[i]["fieldList"][x]["fName"] + ")"
|
||||
field_names_list.append(tbl_list[i]["fieldList"][x]["fDescription"])
|
||||
struct_fields_list.append(tbl_list[i]["fieldList"][x]["fName"])
|
||||
field_names_list.append([tbl_list[i]["fieldList"][x]["fName"], tbl_list[i]["fieldList"][x]["fDescription"]])
|
||||
#struct_fields_list.append(tbl_list[i]["fieldList"][x]["fName"])
|
||||
struct_fields_list.append([tbl_list[i]["fieldList"][x]["fName"], fieldTypeConvert(tbl_list[i]["fieldList"][x]["fType"]), ])
|
||||
if tbl_list[i]["fieldList"][x]["relation"]:
|
||||
relation_list=[tbl_list[i]["fieldList"][x]["fName"]]
|
||||
relation_list.append(tbl_list[i]["fieldList"][x]["relation"])
|
||||
|
@ -156,6 +159,7 @@ def selectData(tbl):
|
|||
for item in tbl_struct_list:
|
||||
if item[0] == tbl:
|
||||
for field in item[1]:
|
||||
field = field[0]
|
||||
qwery = qwery + field + ","
|
||||
for rel in item[2]:
|
||||
field = rel[0]
|
||||
|
@ -182,16 +186,104 @@ def selectData(tbl):
|
|||
qwery = qwery.rstrip(',') + " FROM " + tbl + " LIMIT 10000"
|
||||
#print(qwery)
|
||||
c.execute(qwery)
|
||||
|
||||
return c.fetchall()
|
||||
|
||||
# получаем на вход имя таблицы и возвращаем список заголовков полей
|
||||
def getTableStructure(tbl):
|
||||
global tbl_descr_list
|
||||
global tbl_descr_list, tbl_struct_list
|
||||
#print(tbl_descr_list)
|
||||
#print(tbl_struct_list)
|
||||
for item in tbl_descr_list:
|
||||
if item[0] == tbl:
|
||||
return item[1]
|
||||
|
||||
# Получаем список названий полей и типов для заданной таблицы
|
||||
def getFields(tbl):
|
||||
global tbl_descr_list, tbl_struct_list
|
||||
#print(tbl_descr_list)
|
||||
#print(tbl_struct_list)
|
||||
for item in tbl_struct_list:
|
||||
if item[0] == tbl:
|
||||
#print(item[1])
|
||||
return item[1]
|
||||
# Ищем описание поля по его названию и возвращаем.
|
||||
def getFieldDescription(tbl, field):
|
||||
global tbl_descr_list, tbl_struct_list
|
||||
for item in tbl_descr_list:
|
||||
if item[0] == tbl:
|
||||
for i in item[1]:
|
||||
if i[0] == field:
|
||||
fName = i[1]
|
||||
return fName
|
||||
return "null"
|
||||
|
||||
def fieldTypeConvert(ftype):
|
||||
# разбираем строку на тип и длину
|
||||
ftype = str.lower(ftype)
|
||||
line = re.search("(.+?)\(([0-9]+)\)", ftype)
|
||||
if line:
|
||||
fType = line.groups()[0]
|
||||
fLength = line.groups()[1]
|
||||
if fType == 'int' or fType == 'integer':
|
||||
fType = 'integer'
|
||||
elif fType == 'char' or fType == 'varchar':
|
||||
fType = 'character'
|
||||
else:
|
||||
fType = ftype
|
||||
return fType
|
||||
|
||||
def getFieldType(tbl, field):
|
||||
global tbl_descr_list, tbl_struct_list
|
||||
#print(tbl_descr_list)
|
||||
#print(tbl_struct_list)
|
||||
for item in tbl_struct_list:
|
||||
if item[0] == tbl:
|
||||
for i in item[1]:
|
||||
if i[0] == field:
|
||||
fType = i[1]
|
||||
return fType
|
||||
#print(item[1])
|
||||
#return item[1]
|
||||
|
||||
# добавление записи в БД на вход принимает список вида:
|
||||
# [table [['field_1', 'значение'], ['field_2', 'значение'],....., ['field_n', 'значение']]]
|
||||
def insertDataIntoBD(dataList):
|
||||
global c
|
||||
dbConnect()
|
||||
tableName = dataList[0]
|
||||
|
||||
#datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
|
||||
|
||||
qwery = 'INSERT INTO ' + tableName + ' ('
|
||||
qweryData = ''
|
||||
qweryField = ''
|
||||
for item in dataList[1]:
|
||||
fType = getFieldType(tableName, item[0])
|
||||
#print(fType)
|
||||
qweryField = qweryField + item[0] + ','
|
||||
if fType == 'integer':
|
||||
qweryData = qweryData + '' + item[1] + ','
|
||||
elif fType == 'datetime':
|
||||
#преобразуем дату всяко разно
|
||||
dt = datetime.strptime(item[1], "%d.%m.%Y %H:%M")
|
||||
item[1] = str(dt)
|
||||
qweryData = qweryData + '\'' + item[1] + '\','
|
||||
elif fType == 'date':
|
||||
d = item[1].split('.')
|
||||
myDate = d[2] + '-' + d[1] + '-' + d[1]
|
||||
item[1] = str(myDate)
|
||||
qweryData = qweryData + '\'' + item[1] + '\','
|
||||
else:
|
||||
qweryData = qweryData + '\'' + item[1] + '\','
|
||||
|
||||
qwery = qwery + qweryField.rstrip(',') + ')' + ' VALUES (' + qweryData.rstrip(',') + ');'
|
||||
|
||||
print(qwery)
|
||||
c.execute(qwery)
|
||||
#c.close()
|
||||
return
|
||||
|
||||
|
||||
#initDBstructure()
|
||||
firstInit()
|
||||
dbConnect()
|
||||
dbConnect()
|
||||
|
|
183
gui.py
183
gui.py
|
@ -20,7 +20,7 @@ class MyTable(QTableWidget):
|
|||
#self.horizontalHeader().setSectionResizeMode(1)
|
||||
# изменение ширины столбцов по размеру текста
|
||||
#self.horizontalHeader().setSectionResizeMode(3)
|
||||
self.horizontalHeader().setStyleSheet("color: blue;")
|
||||
self.horizontalHeader().setStyleSheet("color: black; font-weight:bold; background-color: lightblue;")
|
||||
self.setWordWrap(True)
|
||||
self.setSortingEnabled(True)
|
||||
|
||||
|
@ -52,71 +52,138 @@ class MyTable(QTableWidget):
|
|||
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
|
||||
|
||||
# Форма для добавления и редактирования
|
||||
class EditForm_(QWidget):
|
||||
def __init__(self, tblName, tblDescr):
|
||||
super().__init__()
|
||||
#scrollArea = QScrollArea()
|
||||
l = QVBoxLayout()
|
||||
headBox = QHBoxLayout()
|
||||
lblHeader = QLabel('Таблица:' + tblDescr)
|
||||
l.addLayout(headBox)
|
||||
headBox.addWidget(lblHeader)
|
||||
hboxBtn = QHBoxLayout()
|
||||
btnOk = QPushButton('Записать')
|
||||
btnOk.clicked.connect(lambda: self.function1())
|
||||
btnCancel = QPushButton('Закрыть')
|
||||
btnCancel.clicked.connect(lambda: self.close())
|
||||
i=0
|
||||
while i < 30:
|
||||
hboxEdit1 = QHBoxLayout()
|
||||
lbl1 = QLabel(str(i))
|
||||
edit1 = QLineEdit()
|
||||
#edit1.setMaxLength(30)
|
||||
hboxEdit1.addWidget(lbl1)
|
||||
hboxEdit1.addWidget(edit1)
|
||||
l.addLayout(hboxEdit1)
|
||||
i = i+1
|
||||
|
||||
hboxBtn.addWidget(btnOk)
|
||||
hboxBtn.addWidget(btnCancel)
|
||||
l.addLayout(hboxBtn)
|
||||
|
||||
self.setWindowTitle("Добавление записи")
|
||||
self.setLayout(l)
|
||||
self.setFixedSize(640, 480)
|
||||
#scrollArea.setWidget(self)
|
||||
#self.setCentralWidget(scrollArea)
|
||||
|
||||
self.show()
|
||||
|
||||
|
||||
class EditForm(QMainWindow):
|
||||
lblList = []
|
||||
editList = []
|
||||
def __init__(self, tblName, tblDescr):
|
||||
super().__init__()
|
||||
self.tblName = tblName
|
||||
self.setWindowTitle("Добавление записи")
|
||||
scroll_widget = QWidget()
|
||||
self.general_layout = QVBoxLayout()
|
||||
scroll_area = QScrollArea()
|
||||
|
||||
l = QVBoxLayout()
|
||||
headBox = QHBoxLayout()
|
||||
lblHeader = QLabel('Таблица: ' + tblDescr)
|
||||
lblHeader = QLabel("<B>Таблица: " + tblDescr)
|
||||
l.addLayout(headBox)
|
||||
#palet = QPalette(lblHeader.palette())
|
||||
#lblHeader.setPalette(palet)
|
||||
headBox.addWidget(lblHeader)
|
||||
hboxBtn = QHBoxLayout()
|
||||
btnOk = QPushButton('Записать')
|
||||
btnOk.clicked.connect(lambda: self.function1())
|
||||
btnOk.clicked.connect(lambda: self.save())
|
||||
btnCancel = QPushButton('Закрыть')
|
||||
btnCancel.clicked.connect(lambda: self.close())
|
||||
# цифровой валидатор, для проверки ввода
|
||||
integerRegex = QRegExp("^[0-9]+$")
|
||||
integerValidator = QRegExpValidator(integerRegex, self)
|
||||
# список соответствия полей и QEdit
|
||||
self.widgetsList = []
|
||||
# добавляем динамически поля на форму в зависимости от типов данных
|
||||
for item in dm.getFields(tblName):
|
||||
#print(item)
|
||||
fName = item[0]
|
||||
fType = item[1]
|
||||
fDescr = dm.getFieldDescription(tblName, fName)
|
||||
hboxEdit = QHBoxLayout()
|
||||
lbl = QLabel(fDescr)
|
||||
# создаем поле ввода соответсвующее типу данных
|
||||
if fType == 'datetime':
|
||||
edit = QDateTimeEdit()
|
||||
edit.setCalendarPopup(True)
|
||||
edit.setFrame(False)
|
||||
now = QDateTime.currentDateTime()
|
||||
edit.setDateTime(now)
|
||||
elif fType == 'date':
|
||||
edit = QDateEdit()
|
||||
edit.setCalendarPopup(True)
|
||||
edit.setFrame(False)
|
||||
now = QDate.currentDate()
|
||||
edit.setDate(now)
|
||||
elif fType == 'time':
|
||||
edit = QTimeEdit()
|
||||
edit.setCalendarPopup(True)
|
||||
edit.setFrame(False)
|
||||
now = QTime.currentTime()
|
||||
edit.setTime(now)
|
||||
elif fType == 'integer':
|
||||
edit = QLineEdit()
|
||||
# проверка на ввод цифр
|
||||
edit.setValidator(integerValidator)
|
||||
else:
|
||||
edit = QLineEdit()
|
||||
# создаём список полей и соответсвующих им QEdit
|
||||
self.widgetsList.append([fName, edit])
|
||||
|
||||
hboxEdit.addWidget(lbl)
|
||||
hboxEdit.addWidget(edit)
|
||||
l.addLayout(hboxEdit)
|
||||
print(self.widgetsList)
|
||||
hboxBtn.addWidget(btnOk)
|
||||
hboxBtn.addWidget(btnCancel)
|
||||
l.addLayout(hboxBtn)
|
||||
|
||||
self.general_layout.addLayout(l)
|
||||
|
||||
scroll_widget.setLayout(self.general_layout)
|
||||
scroll_area.setWidget(scroll_widget)
|
||||
self.setCentralWidget(scroll_area)
|
||||
|
||||
def save(self):
|
||||
listData = [self.tblName]
|
||||
listFieldData = []
|
||||
for item in self.widgetsList:
|
||||
#print(item[0] + ' ' + item[1].text())
|
||||
listFieldData.append([item[0], item[1].text()])
|
||||
listData.append(listFieldData)
|
||||
#print(listData)
|
||||
dm.insertDataIntoBD(listData)
|
||||
self.close()
|
||||
|
||||
|
||||
|
||||
class EditForm_(QMainWindow):
|
||||
def __init__(self, tblName, tblDescr):
|
||||
super().__init__()
|
||||
self.setWindowTitle("Добавление записи")
|
||||
scroll_widget = QWidget()
|
||||
self.general_layout = QVBoxLayout()
|
||||
scroll_area = QScrollArea()
|
||||
|
||||
l = QVBoxLayout()
|
||||
headBox = QHBoxLayout()
|
||||
lblHeader = QLabel("<B>Таблица: " + tblDescr)
|
||||
l.addLayout(headBox)
|
||||
#palet = QPalette(lblHeader.palette())
|
||||
#lblHeader.setPalette(palet)
|
||||
headBox.addWidget(lblHeader)
|
||||
hboxBtn = QHBoxLayout()
|
||||
btnOk = QPushButton('Записать')
|
||||
btnOk.clicked.connect(lambda: self.save())
|
||||
btnCancel = QPushButton('Закрыть')
|
||||
btnCancel.clicked.connect(lambda: self.close())
|
||||
|
||||
# ПРОВЕРКА ВВОДА, добавить в цикл генерации формы в зависимости от типа поля
|
||||
# grid_layout.addWidget(QLabel("Введите IP-адрес", self), 0, 0)
|
||||
#
|
||||
# ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" # Часть регулярного выржение
|
||||
# # Само регулярное выражение
|
||||
# ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$")
|
||||
# ipValidator = QRegExpValidator(ipRegex, self) # Валидатор для QLineEdit
|
||||
#
|
||||
# lineEdit = QLineEdit()
|
||||
# lineEdit.setValidator(ipValidator) # Устанавливаем валидатор
|
||||
|
||||
i=0
|
||||
for item in dm.getTableStructure(tblName):
|
||||
print(item)
|
||||
hboxEdit1 = QHBoxLayout()
|
||||
lbl1 = QLabel(item)
|
||||
edit1 = QLineEdit()
|
||||
#edit1.setMaxLength(30)
|
||||
hboxEdit1.addWidget(lbl1)
|
||||
hboxEdit1.addWidget(edit1)
|
||||
l.addLayout(hboxEdit1)
|
||||
#print(item)
|
||||
hboxEdit = QHBoxLayout()
|
||||
lbl = QLabel(item)
|
||||
edit = QLineEdit()
|
||||
hboxEdit.addWidget(lbl)
|
||||
hboxEdit.addWidget(edit)
|
||||
l.addLayout(hboxEdit)
|
||||
i = i+1
|
||||
|
||||
hboxBtn.addWidget(btnOk)
|
||||
|
@ -129,14 +196,8 @@ class EditForm(QMainWindow):
|
|||
scroll_area.setWidget(scroll_widget)
|
||||
self.setCentralWidget(scroll_area)
|
||||
|
||||
self.setWindowTitle("Добавление записи")
|
||||
#self.setFixedSize(640, 480)
|
||||
#scrollArea.setWidget(self)
|
||||
#self.setCentralWidget(scrollArea)
|
||||
|
||||
#self.show()
|
||||
|
||||
|
||||
def save(self):
|
||||
print(self.children())
|
||||
|
||||
def addDataIntoTable(tbl_descr, tblDataWidget):
|
||||
global tblList
|
||||
|
@ -148,6 +209,7 @@ def addDataIntoTable(tbl_descr, tblDataWidget):
|
|||
data = dm.selectData(tbl_name)
|
||||
#print(data)
|
||||
fieldNames = dm.getTableStructure(tbl_name)
|
||||
print(fieldNames)
|
||||
# проверка на наличие записей в таблице
|
||||
if data:
|
||||
# количество строк
|
||||
|
@ -161,9 +223,12 @@ def addDataIntoTable(tbl_descr, tblDataWidget):
|
|||
tblDataWidget.setRowCount(rows)
|
||||
tblDataWidget.setColumnCount(cols)
|
||||
for item in fieldNames:
|
||||
fieldNames = item + ','
|
||||
fName = item[0]
|
||||
fDescr = item[1]
|
||||
#fieldNames = item + ','
|
||||
# установка заголовков столбцов таблицы
|
||||
tblDataWidget.setHorizontalHeaderItem(n, QTableWidgetItem(item))
|
||||
#item = '<b>' + item + '</b>'
|
||||
tblDataWidget.setHorizontalHeaderItem(n, QTableWidgetItem(fDescr))
|
||||
n = n + 1
|
||||
|
||||
n = 0
|
||||
|
|
Loading…
Reference in New Issue
Block a user