如何以正确的方式管理不断增长的Python3 / SQLite3 / tkinter代码?

时间:2018-11-14 13:31:18

标签: python python-3.x tkinter sqlite ttk

我是Python的新手,我正在为自己制作一个桌面应用程序。我的窗口之一是“添加公司”。这是屏幕截图:https://ibb.co/hgyFAL

到目前为止,我正在从用户收集数据,并使用以下代码存储在SQLite3中:

 <?php require('includes/config.php');
if(!$user->is_logged_in()){ header('Location: login.php'); exit(); }

if (isset($_POST['submit'])) {

    $stmt = $db->prepare('SELECT * FROM homeworks WHERE homeworkID = :id');
    $stmt->execute(array(':id' => $_POST['hwid']));
    $row2save = $stmt->fetch(PDO::FETCH_ASSOC);;
    $username = $row2save['owner'];
    if ($username === $_SESSION['username']) {
        $done = 0;
        if ($_POST['done'] === 1) {
            $done = 1;
        }
        $stmt = $db->prepare('UPDATE homeworks
      SET name = :name, details = :details, donedate = :donedate, done = :done
      WHERE homeworkID = :id');
        $stmt->execute(array(':id' => $_POST['hwid'], ':name' => $_POST['hwtitle'], ':details' => $_POST['hwdetails'], ':donedate' => $_POST['hwdonedate'], ':done' => $done));
    } else {
        $params = session_get_cookie_params();
        setcookie(session_name('USERNAME'),'RESTRICTED',1,
            isset($params['path']),
            isset($params['domain']),
            isset($params['secure']),
            isset($params['httponly']));
        header('Location: memberpage.php?restricted='.$row2save['owner']);

    }
} else {
    echo 'Error! No form inputs found!';
}
?>

直到上周,我不在乎代码是否正确。但是应用程序正在增长,我担心将来无法管理代码。实际上,即使现在我也无法管理,它只有3个窗口。 :/

因此,我开始问自己“如何做得更好”,然后我在互联网上搜索了我的问题。我找到了好的资源和好的建议,并使用以下代码更新了代码:

import sqlite3 as sql
import os


def create_new_company(
    name,
    address,
    district,
    city,
    country,
    general_email,
    phone1,
    phone2,
    fax,
    tax_number,
    tax_administration,
    activity_area,
    contact,
    contact_task,
    is_client,
    is_supplier,
    is_in_mail_list,
    is_in_sms_list,
    is_in_black_list,
    note,
    is_active):

    db = sql.connect(str(os.getcwd() + '\\Databases\\main_db.sqlite3'))
    cursor = db.cursor()

    cursor.execute("""CREATE TABLE IF NOT EXISTS `companies` (
    `company_id`    INTEGER NOT NULL DEFAULT 0000001 PRIMARY KEY AUTOINCREMENT UNIQUE,
    `name`  TEXT,
    `address`   TEXT,
    `district`  TEXT,
    `city`  TEXT,
    `country`   TEXT,
    `general_email` TEXT,
    `phone1`    NUMERIC,
    `phone2`    NUMERIC,
    `fax`   NUMERIC,
    `tax_number`    TEXT,
    `tax_administration`    NUMERIC,
    `activity_area` TEXT,
    `contact`   TEXT,
    `contact_task`  TEXT,
    `is_client` INTEGER,
    `is_supplier`   INTEGER,
    `is_in_mail_list`   INTEGER,
    `is_in_sms_list`    NUMERIC,
    `is_in_black_list`  NUMERIC,
    `note`  TEXT,
    `is_active` NUMERIC);""")

    values = (
        name,
        address,
        district,
        city,
        country,
        general_email,
        phone1,
        phone2,
        fax,
        tax_number,
        tax_administration,
        activity_area,
        contact,
        contact_task,
        is_client,
        is_supplier,
        is_in_mail_list,
        is_in_sms_list,
        is_in_black_list,
        note,
        is_active
    )
    script= """INSERT INTO companies VALUES (
    NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"""

    cursor.execute(script, values)
    db.commit()
    db.close()

我认为最近一次更新比较好,基本功能还可以。但是现在我被困在这里,我需要一个路线图。

我想象一个类似下面的函数,但是我无法结束:

class SQLCommands:
    sqlite_file = str(os.getcwd() + '\\test.db')

    def __init__(self):
        if os.path.exists(self.sqlite_file):
            pass
        else:
            self.create_new_database(self.sqlite_file)

    def create_new_database(self, database_path):
        with sqlite3.connect(database_path) as conn:
        c = conn.cursor()

        c.execute("""CREATE TABLE IF NOT EXISTS `companies` (
            `company_id`    INTEGER NOT NULL PRIMARY KEY UNIQUE,
            `name`  TEXT);""")

        self.close(conn)

    def connect(self, database_path):
        with sqlite3.connect(database_path) as conn:
            c = conn.cursor()
            return conn, c

    def close(self, conn):
        conn.commit()
        conn.close()

我想这样使用:

class SQLCommands:
    sqlite_file = str(os.getcwd() + '\\test.db')

    # def other_fucntions
    #     ...some codes here...
    #     .....

    def insert(self, table, column, value):
        conn, c = self.connect(self.sqlite_file)
        values = (value,)
        script = """INSERT INTO {} VALUES (?)""".format(table)  # I'm not sure if the correct way is this

        c.execute(script, value)
        conn.commit()
        conn.close()

        del value, script, conn, c

我的未来目标是学习Django,并通过Django将我的应用程序带到网络上。因此,SQLCommands类一定不能依赖于Tkinter。

我走对了吗?这是正确的方法吗?如果是,我如何完成代码“ SQLCommands.insert”

我的英语可能不太清楚,但我会尽力而为。

对不起,谢谢。 Alperen

0 个答案:

没有答案