Skip to content

Commit

Permalink
Now support Python3
Browse files Browse the repository at this point in the history
  • Loading branch information
amaork committed Jun 10, 2018
1 parent be8573c commit bf0e1cc
Show file tree
Hide file tree
Showing 25 changed files with 331 additions and 332 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PyAppFramework
========

Python Application Framework (Python 2.7)
Python Application Framework

![PyAppFramewirk chart](chart/PyAppFramework.png)

Expand All @@ -13,7 +13,7 @@ A concise easy to use PySide GUI Application Framework, make you build yourself

## Request

- Python 2.7
- Python3+
- PySide
- pyserial

Expand Down
42 changes: 21 additions & 21 deletions core/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ class SQLiteDatabaseError(Exception):


class SQLiteDatabase(object):
TYPE_INTEGER, TYPE_REAL, TYPE_TEXT, TYPE_BLOB = range(4)
TBL_CID, TBL_NAME, TBL_TYPE, TBL_REQUIRED, TBL_DEF, TBL_PK = range(6)
TYPE_INTEGER, TYPE_REAL, TYPE_TEXT, TYPE_BLOB = list(range(4))
TBL_CID, TBL_NAME, TBL_TYPE, TBL_REQUIRED, TBL_DEF, TBL_PK = list(range(6))

def __init__(self, db_path):
if not os.path.isfile(db_path):
Expand All @@ -29,19 +29,19 @@ def __del__(self):
@staticmethod
def conditionFormat(k, v, t):
t = SQLiteDatabase.detectDataType(t)
data = u'{} = "{}"'.format(k, v) if t == SQLiteDatabase.TYPE_TEXT else u'{} = {}'.format(k, v)
data = '{} = "{}"'.format(k, v) if t == SQLiteDatabase.TYPE_TEXT else '{} = {}'.format(k, v)
return data.encode("utf-8")

@staticmethod
def searchConditionFormat(k, v, t):
t = SQLiteDatabase.detectDataType(t)
data = u'{} LIKE "%{}%"'.format(k, v) if t == SQLiteDatabase.TYPE_TEXT else u'{} LIKE %{}%'.format(k, v)
data = '{} LIKE "%{}%"'.format(k, v) if t == SQLiteDatabase.TYPE_TEXT else '{} LIKE %{}%'.format(k, v)
return data.encode("utf-8")

@staticmethod
def globalSearchConditionFormat(k, v, t):
t = SQLiteDatabase.detectDataType(t)
data = u'{} GLOB "*{}*"'.format(k, v) if t == SQLiteDatabase.TYPE_TEXT else u'{} LIKE *{}*'.format(k, v)
data = '{} GLOB "*{}*"'.format(k, v) if t == SQLiteDatabase.TYPE_TEXT else '{} LIKE *{}*'.format(k, v)
return data.encode("utf-8")

@staticmethod
Expand Down Expand Up @@ -73,7 +73,7 @@ def getTableInfo(self, name):
self.__cursor.execute("PRAGMA table_info({})".format(name))
table_info = self.__cursor.fetchall()
column_list = [x[self.TBL_NAME] for x in table_info]
return dict(zip(column_list, table_info))
return dict(list(zip(column_list, table_info)))

def getColumnList(self, name):
"""Get table column name list
Expand Down Expand Up @@ -148,14 +148,14 @@ def createTable(self, name, columns):

data = list()
for column, type_, is_null, default, pk in columns:
default = u"DEFAULT {}".format(default) if default else ""
default = "DEFAULT {}".format(default) if default else ""
if is_null:
data_format = u"{} {} {}".format(column, type_, default)
data_format = "{} {} {}".format(column, type_, default)
else:
data_format = u"{} {} NOT NULL {}".format(column, type_, default)
data_format = "{} {} NOT NULL {}".format(column, type_, default)

if pk:
data_format += u" PRIMARY KEY"
data_format += " PRIMARY KEY"

data.append(data_format)

Expand Down Expand Up @@ -187,12 +187,12 @@ def insertRecord(self, name, record):
blob_records = list()
for column, data, type_ in zip(column_names, record, column_types):
if type_ == self.TYPE_TEXT:
recode_data.append(u'"{}"'.format(data))
recode_data.append('"{}"'.format(data))
elif type_ == self.TYPE_BLOB:
recode_data.append(u"?")
recode_data.append("?")
blob_records.append(data)
else:
recode_data.append(u"{}".format(data))
recode_data.append("{}".format(data))

recode_data = ", ".join(recode_data).encode("utf-8")

Expand Down Expand Up @@ -237,23 +237,23 @@ def updateRecord(self, name, where, record):
if isinstance(record, (list, tuple)):
for column, data, type_ in zip(column_names, record, column_types):
if type_ == self.TYPE_TEXT:
recode_data.append(u'{} = "{}"'.format(column, data))
recode_data.append('{} = "{}"'.format(column, data))
elif type_ == self.TYPE_BLOB:
blob_records.append(data)
recode_data.append(u"{} = ?".format(column, data))
recode_data.append("{} = ?".format(column, data))
else:
recode_data.append(u"{} = {}".format(column, data))
recode_data.append("{} = {}".format(column, data))
# Update particular data by column name
else:
for column_name, data in record.items():
for column_name, data in list(record.items()):
type_ = column_types[column_names.index(column_name)]
if type_ == self.TYPE_TEXT:
recode_data.append(u'{} = "{}"'.format(column_name, data))
recode_data.append('{} = "{}"'.format(column_name, data))
elif type_ == self.TYPE_BLOB:
blob_records.append(data)
recode_data.append(u"{} = ?".format(column_name, data))
recode_data.append("{} = ?".format(column_name, data))
else:
recode_data.append(u"{} = {}".format(column_name, data))
recode_data.append("{} = {}".format(column_name, data))

pk_name = pk_name.encode("utf-8")
recode_data = ", ".join(recode_data).encode("utf-8")
Expand Down Expand Up @@ -297,7 +297,7 @@ def selectRecord(self, name, columns=None, conditions=None):
if not isinstance(columns, (list, tuple)):
raise TypeError("columns require list or tuple")

if not isinstance(conditions, (str, unicode)):
if not isinstance(conditions, str):
raise TypeError("conditions require string object")

# Pre process
Expand Down
13 changes: 6 additions & 7 deletions core/datatype.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
import json
import types
import ctypes
import xml.etree.ElementTree as XmlElementTree
__all__ = ['BasicDataType', 'BasicTypeLE', 'BasicTypeBE', 'DynamicObject', 'ComparableXml',
Expand All @@ -10,25 +9,25 @@


def str2float(text):
if isinstance(text, (int, long, float)):
if isinstance(text, (int, float)):
return text

if not isinstance(text, types.StringTypes):
if not isinstance(text, str):
return 0

try:

return float(text)

except StandardError:
except Exception:
return 0.0


def str2number(text):
if isinstance(text, (bool, int, long, float)):
if isinstance(text, (bool, int, float)):
return text

if not isinstance(text, types.StringTypes):
if not isinstance(text, str):
return 0

try:
Expand All @@ -52,7 +51,7 @@ def str2number(text):
else:
return int(text)

except StandardError:
except Exception:
return 0


Expand Down
46 changes: 21 additions & 25 deletions core/uimailbox.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# -*- coding: utf-8 -*-
import types
from threading import Timer
from ..gui.msgbox import MB_TYPES, showMessageBox
from PySide.QtCore import Qt, Signal, Slot, QObject
Expand All @@ -8,26 +7,26 @@


class BaseUiMail(object):
def __init__(self, context=""):
if not isinstance(context, types.StringTypes):
raise RuntimeError("Mail context TypeError:{0:s}".format(context.__class__.__name__))
self.__context = context
def __init__(self, content=""):
if not isinstance(content, str):
raise RuntimeError("Mail context TypeError:{0:s}".format(content.__class__.__name__))
self.__content = content

@property
def context(self):
return self.__context
def content(self):
return self.__content


class StatusBarMail(BaseUiMail):
def __init__(self, color, context, timeout=0):
def __init__(self, color, content, timeout=0):
""" Show message on statusBar
:param color: Message color
:param context: Message context
:param content: Message content
:param timeout: Message display time(second)
:return:
"""
super(StatusBarMail, self).__init__(context)
super(StatusBarMail, self).__init__(content)
if not isinstance(color, (QColor, Qt.GlobalColor)):
raise RuntimeError("StatusBar mail color TypeError:{0:s}".format(color.__class__.__name__))

Expand All @@ -47,21 +46,18 @@ def timeout(self):


class MessageBoxMail(BaseUiMail):
def __init__(self, type_, title, context):
""" Show QMessageBox with #title and #context
def __init__(self, type_, content, title=None):
""" Show QMessageBox with #title and #content
:param type_: QMessageBox types ["info", "error", "warning"]
:param content: QMessageBox context
:param title: QMessageBox title
:param context: QMessageBox context
:return:
"""
super(MessageBoxMail, self).__init__(context)
super(MessageBoxMail, self).__init__(content)
if type_ not in MB_TYPES:
raise RuntimeError("MessageBox mail message type TypeError:{}".format(type_))

if not isinstance(title, types.StringTypes):
raise RuntimeError("MessageBox mail title TypeError:{0:s}".format(title.__class__.__name__))

self.__type = type_
self.__title = title

Expand All @@ -75,13 +71,13 @@ def title(self):


class WindowsTitleMail(BaseUiMail):
def __init__(self, context):
"""Show a message on windows title with #context
def __init__(self, content):
"""Show a message on windows title with #content
:param context: message context
:param content: message content
:return:
"""
super(WindowsTitleMail, self).__init__(context)
super(WindowsTitleMail, self).__init__(content)


class CallbackFuncMail(BaseUiMail):
Expand Down Expand Up @@ -166,7 +162,7 @@ def mailProcess(self, mail):
color = "rgb({0:d},{1:d},{2:d})".format(mail.color.red(), mail.color.green(), mail.color.blue())
# Main windows has status bar
if isinstance(self.__parent.ui.statusbar, QStatusBar):
self.__parent.ui.statusbar.showMessage(self.tr(mail.context), mail.timeout)
self.__parent.ui.statusbar.showMessage(self.tr(mail.content), mail.timeout)
self.__parent.ui.statusbar.setStyleSheet(
"QStatusBar{"
"padding-left:8px;"
Expand All @@ -175,7 +171,7 @@ def mailProcess(self, mail):
"font-weight:bold;}" % color)
# Widget has label named as statusbar
elif isinstance(self.__parent.ui.statusbar, QLabel):
self.__parent.ui.statusbar.setText(self.tr(mail.context))
self.__parent.ui.statusbar.setText(self.tr(mail.content))
self.__parent.ui.statusbar.setStyleSheet(
"color:{0:s};padding-top:8px;font-weight:bold;".format(color)
)
Expand All @@ -188,11 +184,11 @@ def mailProcess(self, mail):

# Show a message box
elif isinstance(mail, MessageBoxMail):
showMessageBox(self.__parent, mail.type, mail.title, mail.context)
showMessageBox(mail.type, mail.content, mail.title)

# Appended a message on windows title
elif isinstance(mail, WindowsTitleMail):
self.__parent.setWindowTitle(self.__parent.windowTitle() + self.tr(" {0:s}".format(mail.context)))
self.__parent.setWindowTitle(self.__parent.windowTitle() + self.tr(" {0:s}".format(mail.content)))

# Callback function
elif isinstance(mail, CallbackFuncMail):
Expand Down
11 changes: 5 additions & 6 deletions demos/button_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,22 @@ def __init__(self, parent=None):
self.setWindowTitle("Button Demo")

def slotAddButton(self):
buttonText = self.buttonSelect.currentText().encode("ascii")
buttonText = self.buttonSelect.currentText()
typeIndex = self.buttonList.index(buttonText)
buttonTextGroup = ("{0:s} ON".format(buttonText), "{0:s} OFF".format(buttonText))
buttonTextGroup = ("{} ON".format(buttonText), "{} OFF".format(buttonText))

state = StateButton(50)
if buttonText == "RoundButton":
button = RoundButton(200, text=buttonTextGroup)
elif buttonText == "IconButton":
all = ""
for name in QImageReader.supportedImageFormats():
all += "*.{0:s} ".format(name)
for name in QImageReader.supportedImageFormats():
all += "*.{} ".format(name)
files, _ = QFileDialog.getOpenFileNames(self,
"Select icon images",
ImagesPath,
"Images(*.jpg)")
if len(files) == 2:
button = IconButton(icons=(files[0], files[1]))
button = IconButton(icons=files)
else:
button = self.buttonType[typeIndex](200, 50, text=buttonTextGroup)

Expand Down
6 changes: 3 additions & 3 deletions demos/container_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def __init__(self, parent=None):
self.countrySequence.sequenceChanged.connect(self.__slotGetSequenceText)

layout = QVBoxLayout()
for item in self.countrySequence.items():
for item in list(self.countrySequence.items()):
layout.addWidget(item)

layout1 = QGridLayout()
Expand Down Expand Up @@ -69,10 +69,10 @@ def __slotSetEditable(self, editable):
self.countrySequence.setEditable(editable)

def __slotGetSequence(self):
self.sequenceLabel.setText("{0:s}".format(self.countrySequence.getSequence()))
self.sequenceLabel.setText("{}".format(self.countrySequence.getSequence()))

def __slotGetSequenceText(self):
self.textLabel.setText("{0:s}".format(self.countrySequence.getSequenceText()))
self.textLabel.setText("{}".format(self.countrySequence.getSequenceText()))


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions demos/crc16_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@
# B251
crc2 = crc.crc16(string)

print "Data: 0x{0:x}, crc16: 0x{1:x}, result: {2:b}".format(data, crc1, crc1 == 0x9d78)
print "String: {0:s}, crc16: 0x{1:x}, result: {2:b}".format(string, crc2, crc2 == 0xb251)
print("Data: 0x{0:x}, crc16: 0x{1:x}, result: {2:b}".format(data, crc1, crc1 == 0x9d78))
print("String: {0:s}, crc16: 0x{1:x}, result: {2:b}".format(string, crc2, crc2 == 0xb251))
2 changes: 1 addition & 1 deletion demos/ftpclient_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

if __name__ == '__main__':
address = socket.gethostbyname("speedtest.tele2.net")
print "Start connect ftp://speedtest.tele2.net({0:s}), please wait...".format(address)
print("Start connect ftp://speedtest.tele2.net({0:s}), please wait...".format(address))

ftp = FTPClient(address, timeout=60, verbose=True)
print(ftp.get_file_list("/"))
3 changes: 1 addition & 2 deletions demos/msgbox_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ def __init__(self, parent=None):
self.setWindowTitle("MessageBox Demo")

def slotShowMessageBox(self):
showMessageBox(self, self.messageType.currentText().encode("ascii"),
self.titleEdit.text().encode("ascii"), self.contextEdit.text().encode("ascii"))
showMessageBox(self.messageType.currentText(), self.contextEdit.text(), self.titleEdit.text())


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion demos/serial_transfer_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import print_function

import sys
import argparse
from ..protocol.serialport import SerialTransferProtocol, SerialPort, SerialTransferError
Expand Down
6 changes: 3 additions & 3 deletions demos/setup_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@


if __name__ == "__main__":
print "Commit count:{0:d}".format(get_git_commit_count())
print "Release hash:{0:s}".format(get_git_release_hash())
print "Release data:{0:s}".format(get_git_release_date())
print("Commit count:{0:d}".format(get_git_commit_count()))
print("Release hash:{0:s}".format(get_git_release_hash()))
print("Release data:{0:s}".format(get_git_release_date()))
Loading

0 comments on commit bf0e1cc

Please sign in to comment.