python工具开发项目通用框架

前言

在看同事的代码时,学习到一套非常好用的框架,写个博客记录一下

框架内容一览

框架结构
在这里插入图片描述

config:用于存放一些配置,不过现在配置基本改为yaml了,不再使用json方式去存储一些配置
ground:为service提供的方法,调用tool文件夹中的mysql.py来封装一些项目需求的sql语句,在此层尽可能的提供返回结果
service:所有方法来源于ground,这一层相当于后端的接口,对传入的参数都会进行判断处理,然后直接返回来自ground的结果
sql:初始化数据库的一些建表语句
tool:公用文件的封装,例如封装了数据库、读json文件、读yaml文件,这里尽量不要写死一些数据,保证是通用的,无论哪个项目都可以使用的,mysql文件中的数据库信息也可以不写死,mysql依赖于read_config.py,通过read_config.py的方法读取config文件夹中存储的数据库信息,所以保证通用性,并且这个文件夹中提供的方法也必须要最大通用化,例如read_config.py中提供修改config文件夹中的数据,形参是“name”和“key”,不写死
view:这里存放的就是UI的界面了
main.py:是程序入口,很简单几句话,就是显示了第一个窗口
untitled_business.py:则是页面业务实现逻辑了
框架内容详情
tool:mysql.py
import pymysql
from tool.read_config import Read_Config


class My_Sql():
    read_config = Read_Config()
    db_ip = read_config.config_get_value('db_ip')
    db_port = read_config.config_get_value('db_port')
    db_username = read_config.config_get_value('db_username')
    db_password = read_config.config_get_value('db_password')
    db_name = read_config.config_get_value('db_name')
    db_charset = read_config.config_get_value('db_charset')

    def __init__(self):
        self.conn = pymysql.connect(host=My_Sql.db_ip, user=My_Sql.db_username, password=My_Sql.db_password,
                        database=My_Sql.db_name, port=My_Sql.db_port)
        self.cursor = self.conn.cursor()

    def close_db_connect(self):
        if self.conn is not None:
            self.conn.close()
        if self.cursor is not None:
            self.cursor.close()

    def batch_execution_sql(self, sql_list):
        for x in sql_list:
            try:
                self.cursor.execute(x)
            except pymysql.Error as e:
                return e
            finally:
                self.conn.close()

    def select_sql_one(self, sql):
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchone()
        except pymysql.Error as e:
            return e
        finally:
            self.conn.close()

    def select_sql_all(self, sql):
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except pymysql.Error as e:
            return e
        finally:
            self.conn.close()

    def update_sql(self, sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            return self.cursor.fetchone()
        except pymysql.Error as e:
            return e
        finally:
            self.conn.close()
tool:read_config.py

我这里是做了一个容错,self.dict_config是为了防止第一次运行时没带这个配置项,或者说删除了这个配置项,其实这里不应该带这个变量的,毕竟这样就写死了一些东西

import json
import os.path


class Read_Config():
    def __init__(self):
        self.path = './config/app_config.json'
        self.dict_config = {
            "db_ip": "localhost",
            "db_port": 3306,
            "db_username": "",
            "db_password": "",
            "db_name": "",
            "db_charset": "utf-8",
            "remember_password": 0,
            "user": {
                "username": "",
                "password": ""
            },
            "auto_login": 0
        }
        if os.path.exists(self.path):
            with open(self.path, 'r+', encoding='utf-8') as f:
                text = f.read()
                self.config = json.loads(text)
        else:
            with open(self.path, "a+", encoding='utf-8') as f:
                json.dump(self.dict_config, f)

    def config_get_value(self, name):
        return self.config.get(name)

    def read_config(self):
        self.dict_config.clear()
        with open(self.path, 'r') as f:
            self.dict_config = json.load(f)
            f.close()

    def config_set_value(self, name, key):
        self.read_config()
        with open(self.path, "w+", encoding='utf-8') as w:
            self.dict_config.pop(name)
            self.dict_config[name] = key
            json.dump(self.dict_config, w, ensure_ascii=False)

    def config_set_list_value(self, name, key, repetition=False) -> None:  # 用于修改列表json数据,并将数据添加至列表末尾
        """
        :param name:
        :param key:
        :param repetition: 是否支持重复,重复直接在末尾添加,不支持重复则先删除重复再添加
        :return:
        """
        self.read_config()
        with open(self.path, "w+", encoding='utf-8') as w:
            raw_value = self.dict_config.get(name)
            if isinstance(raw_value, list):
                if repetition:
                    try:
                        raw_value.index(key)
                    except:
                        raw_value.append(key)
                    else:
                        raw_value.pop(raw_value.index(key))
                        raw_value.append(key)
                else:
                    raw_value.append(key)
                self.dict_config.pop(name)
                self.dict_config[name] = raw_value
                json.dump(self.dict_config, w, ensure_ascii=False)
            else:
                return None
ground:user_ground.py
from tool.mysql import My_Sql


class User_Ground():
    @staticmethod
    def select_user(user_name, user_password=None, user_role=None):
        if user_password is None:
            return My_Sql().select_sql_one("select count(*) from user where id= '%s'" % (user_name))[0] == 1
        else:
            return My_Sql().select_sql_one("select count(*) from user where id= '%s' and passwd='%s' and role='%s'" % (
                user_name, user_password, user_role))[0] == 1

    @staticmethod
    def select_all_user():
        user_dict = {}
        user_dict["用户总数"] = My_Sql().select_sql_one("select count(*) from user")[0]
        user_dict["用户信息"] = [x for x in My_Sql().select_sql_all("select id, passwd, role from user")]
        user_dict["管理员数"] = My_Sql().select_sql_one("select count(*) from user where role='admin'")[0]
        return user_dict

    @staticmethod
    def add_user(user_name, user_passwd, role=None):
        if role is None:
            jg = My_Sql().update_sql(
                "insert into user(id,passwd,role) values ('%s','%s','emp')" % (
                user_name, user_passwd))  # update层只有2个结果,要么执行成功返回None要么异常返回异常原因
            if jg is None:
                if \
                        My_Sql().select_sql_one(
                            "select id from user where id='%s' and passwd='%s'" % (user_name, user_passwd))[
                            0] == 1:
                    return True
                else:
                    return False
            else:
                return jg  # 非None则返回异常原因
        else:
            jg = My_Sql().update_sql(
                "insert into user(id,passwd,role) values ('%s','%s','%s')" % (user_name, user_passwd, role))
            if jg is None:
                if My_Sql().select_sql_one(
                        "select count(*) from user where id='%s' and passwd='%s' and role='%s'" % (
                                user_name, user_passwd, role))[0] == 1:
                    return True
                else:
                    return False
            else:
                return jg

    @staticmethod
    def return_admin_user(super_admin=False, super_admin_pass=False):
        if super_admin:
            return My_Sql().select_sql_all("select id from user where role= 'administrator'")[0]
        elif super_admin_pass:
            return My_Sql().select_sql_all("select passwd from user where role= 'administrator'")[0]
        else:
            if My_Sql().select_sql_one("select count(*) from user where role= 'admin' or role='administrator'")[0] == 1:
                return My_Sql().select_sql_all("select id from user where role= 'admin'")[0]
            else:
                return My_Sql().select_sql_all("select id from user where role= 'admin' or role='administrator'")

    @staticmethod
    def del_user(user_name):
        jg = My_Sql().update_sql("delete from user where id ='%s'" % (user_name))
        if jg is None:
            if My_Sql().select_sql_one("select count(*) from user where id ='%s'" % (user_name))[0] == 1:
                return False
            else:
                return True
        else:
            return jg

    @staticmethod
    def update_user(name, role, new_password=None):
        if new_password is not None:
            jg = My_Sql().update_sql(
                "update user set passwd ='%s',role='%s' where id ='%s'" % (new_password, role, name))
            if jg is None:
                if My_Sql().select_sql_one("select count(*) from user where passwd='%s' and id='%s' and role='%s'" % (
                        new_password, name, role))[0] == 1:
                    return True
                else:
                    return False
            else:
                return jg
        else:
            jg = My_Sql().update_sql(
                "update user set role='%s' where id ='%s'" % (role, name))
            if jg is None:
                if My_Sql().select_sql_one("select count(*) from user where id='%s' and role='%s'" % (
                        name, role))[0] == 1:
                    return True
                else:
                    return False
            else:
                return jg

    @staticmethod
    def select_authority(name):
        return My_Sql().select_sql_one("select state from authority where jurisdiction_name= '%s'" % (name))[0] == 1

    @staticmethod
    def update_authority(name, state):
        jg = My_Sql().update_sql("update authority set state = '%s' where jurisdiction_name= '%s'" % (state, name))
        if jg is None:
            return jg
        else:
            return True

    @staticmethod
    def user_authentication(name):
        try:
            My_Sql().select_sql_one("select role from user where id= '%s'" % (name))[0]
        except:
            return None
        else:
            return My_Sql().select_sql_one("select role from user where id= '%s'" % (name))[0]

service:user_service.py

可以看到service层基本是与ground层是一样的,只是service层针对的是业务逻辑封装的方法,而ground层是对数据库查询的一些语句

from ground.user_ground import User_Ground
from ground.user_config_ground import User_Config_Ground


class User_Service():
    @staticmethod
    def login(user_name, user_password, user_role='emp'):
        return User_Ground().select_user(user_name, user_password, user_role)

    @staticmethod
    def select_all_user():
        return User_Ground().select_all_user()

    @staticmethod
    def add_user(user_name, user_password, role=None):
        if user_name is None or user_password is None or user_name == '' or user_password == '':
            return False
        else:
            if role is None:
                return User_Ground().add_user(user_name, user_password)  # add_user层 有3种结果,要么是异常原因 要么为真 要么为假
            else:
                return User_Ground().add_user(user_name, user_password, role)

    @staticmethod
    def return_admin_user(super_admin=False, super_admin_pass=False):
        if super_admin:
            return str(User_Ground().return_admin_user(True)).replace('(\'', '').replace('\',)', '')
        elif super_admin_pass:
            return str(User_Ground().return_admin_user(False, True)).replace('(\'', '').replace('\',)', '')
        else:
            temp_tuple = User_Ground().return_admin_user()
            temp_list = []
            if len(temp_tuple) >= 2:
                for x in temp_tuple:
                    temp_list.append(str(x).replace("(\'", "").replace("\',)", ""))
                return temp_list
            else:
                return temp_tuple

    @staticmethod
    def del_user(user_name):
        if user_name is not None and user_name != '':
            return User_Ground().del_user(user_name)
        else:
            return False

    @staticmethod
    def update_user(name, role, new_password=None):
        if name != '' and role != '' and name is not None and role is not None and new_password != '' and new_password is not None:
            return User_Ground().update_user(name, role, new_password)
        elif name != '' and role != '' and name is not None and role is not None:
            return User_Ground().update_user(name, role)

    @staticmethod
    def update_config(name, key):
        if name != '' and key != '' and name is not None and key is not None:
            User_Config_Ground().update_config(name, key)
            return True
        else:
            return False

    @staticmethod
    def update_remember_password_config(state):
        if state == 1 or state == 0:
            return User_Service().update_config("remember_password", state)
        else:
            return False

    @staticmethod
    def update_auto_login_config(state):
        if state == 1 or state == 0:
            return User_Service().update_config("auto_login", state)
        else:
            return False

    @staticmethod
    def update_user_config(username, password):
        return User_Service().update_config("user", {"username": username, "password": password})

    @staticmethod
    def user_is_exist(user_name):
        return User_Ground().select_user(user_name)

    @staticmethod
    def select_authority(name):
        if name is None or name == '':
            return False
        else:
            return User_Ground().select_authority(name)

    @staticmethod
    def update_authority(name, state):
        if name != "" and state != "" and name is not None and state is not None:
            User_Ground().update_authority(name, state)


    @staticmethod
    def user_authentication(name):
        if name is None or name == '':
            return False
        else:
            return User_Ground().user_authentication(name)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值