def get_users(self): """ 显示用户的信息,用户新建、删除、解锁用户时显示用户基本信息 :return: """ username = my_Common.input_msg("请输入用户名:") # 创建一个用户实例 _deluser = my_clsUsers() _deluser.username = username # 如果用户名存在,load用户信息成功 if _deluser.load_user_info(): # 先显示一下用户的信息 my_Common.show_message( my_template.user_info.format( username=_deluser.username, name=_deluser.name, mobile=_deluser.mobile, role=_deluser.role, isdel="否" if _deluser.isdel == 0 else "是", islocked="否" if _deluser.islocked == 0 else "是", bindcard=_deluser.bindcard), "NOTICE") return _deluser else: my_Common.show_message("用户名不存在!", "ERROR") return False
def init_user_info(self): """ 创建用户,完善用户资料信息 需要创建一个新的对象 :return: """ is_null_flag = True while is_null_flag: self.username = input("登录用户名(小写字母):").strip().lower() if not self.username: my_Common.show_message("用户名不能为空", "ERROR") continue elif self.user_exists: my_Common.show_message("该用户名已存在", "ERROR") continue else: is_null_flag = False continue self.name = my_Common.input_msg("姓名:") self.password = my_Common.input_msg("密码:") self.mobile = my_Common.input_msg("手机:") self.role = my_Common.input_msg("用户权限(user/admin):", ("admin", "user")) self.create_user() #调用创建用户的方法 my_Common.show_message("用户创建成功!", "NOTICE")
def modify_password(self): """ 个人中心 - 修改密码 :return: """ _not_null_flag = False try: while not _not_null_flag: _new_password = input("输入新密码: ").strip() _confirm_password = input("再次输入确认密码:").strip() if not _new_password or not _confirm_password: my_Common.show_message("密码不能为空,请重新输入!", "ERROR") continue if _new_password != _confirm_password: my_Common.show_message("两次输入密码不一致,请重新输入!", "NOTICE") continue _not_null_flag = True self.password = _new_password _password = my_Common.encrypt(self.password) self.dict_user[self.username]["password"] = _password self.update_user() my_Common.show_message("密码修改成功!", "INFORMATIOM") return True except Exception as e: my_Common.write_error_log(e) return False
def load_data_from_db(tabename): """ 从指定的数据表中获取所有数据,通过 json 方式将数据返回 :param tabename: 数据文件名 :return: 返回所有结果 """ try: with open(tabename, 'r+') as f: return json.load(f) except Exception as e: my_Common.write_error_log(e)
def logout(self): """ 注销当前用户,将系统属性置空 :return: """ self.islogin = False self.bindcard = "" self.mobile = "" self.name = "" self.password = "" self.username = "" my_Common.show_message("注销成功", "NOTICE")
def append_db_json(contant, filename): """ 将信息以 json 格式写入数据表文件(追加) :param contant: 要写入的 json 格式内容 :param filename: 要写入的数据表文件名 :return: 无返回 """ try: with open(filename, 'a+') as fa: fa.write(simplejson.dumps(contant, sort_keys=True)) fa.write("\n") except Exception as e: my_Common.write_error_log(e)
def write_db_json(contant, filename): """ 将信息以 json 格式写入数据表文件(覆盖) :param contant: 写入的json数据内容 :param filename: 要写入的文件名 :return: 无返回结果 """ try: with open(filename, 'w+') as fw: fw.write( simplejson.dumps(contant)) #,sort_keys=True,indent=4)) except Exception as e: my_Common.write_error_log(e)
def _user_login(self, password, code): """ 用户登录验证模块,对用户对象进行判断,登录成功后返回一个新的用户对象 :return: """ # 对输入的密码加密 _password = my_Common.encrypt(password) for user, details in self.dict_user.items(): # 找到用户名 if user == self.username and not details["isdel"]: # 是否被锁定 if details["islocked"] == 0: # 账户未锁定,验证密码 if details["password"] == _password and code == self.code: # 对用户对象进行赋值 self.islogin = True # self.bindcard = details["bindcard"] self.name = details["name"] self.mobile = details["mobile"] self.role = details["role"] self.isdel = details["isdel"] self.islocked = details["islocked"] self.password = password break else: # 密码错误,失败1次 self.trycount += 1 else: # 账户锁定了 self.islocked = 1
def init_db_users(self): _db_file = os.path.join(my_conf.DATABASE['dbpath'], 'users.db') for k, v in self._user_dic.items(): temppasswd = self._user_dic[k]['password'] encryptpasswd = my_Common.encrypt(temppasswd) self._user_dic[k]['password'] = encryptpasswd my_jsonhelper.write_db_simplejson(self._user_dic, _db_file) print("Table create successfull".format(_db_file))
def init_database(self): #获取数据文件列表 tables = list(my_conf.DATABASE['tables'].values()) #数据表存放路径 database = my_conf.DATABASE['dbpath'] for _table in tables: if not os.path.exists(os.path.join(database, '{0}.db'.format(_table))): if hasattr(self, 'init_db_{0}'.format(_table)): #反射 init_func = getattr(init_DB, 'init_db_{0}'.format(_table)) init_func(self) else: my_Common.write_error_log( "Table create Error...." + os.path.join(database, '{0}.db'.format(_table))) else: my_Common.show_message(os.path.join(database, '{0}.db'.format(_table), '表已经存在,数据初始化已完成'), "INFORMATION")
def update_user(self): """ 用户数据更新方法,用户修改信息、用户账户锁定、解锁等操作之后更新数据库文件 :return: """ try: ''' _password = my_Common.encrypt(self.password) self.dict_user[self.username]["password"] = _password self.dict_user[self.username]["islocked"] = self.islocked self.dict_user[self.username]["name"] = self.name self.dict_user[self.username]["mobile"] = self.mobile self.dict_user[self.username]["bindcard"] = self.bindcard self.dict_user[self.username]["isdel"] = self.isdel self.dict_user[self.username]["role"] = self.role ''' # 写入数据库文件 my_jsonhelper.write_db_simplejson(self.dict_user, self.__database) return True except Exception as e: my_Common.write_error_log(e) return False
def create_user(self): """ 新创建一个用户,将用户数据同步写入到数据库文件 :return: """ self.dict_user[self.username] = dict(password=my_Common.encrypt(self.password), name=self.name, mobile=self.mobile, # bindcard=self.bindcard, role=self.role, islocked=0, isdel=0, ) my_jsonhelper.write_db_simplejson(self.dict_user, self.__database)
def __init__(self): # print(self.__database) self.username = "" # 登录名 self.password = "" # 登录密码 self.bindcard = "" # 绑定卡 self.islogin = False # 登录状态 self.name = "" # 姓名 self.mobile = "" # 手机 self.islocked = 0 # 是否锁定 self.role = "user" # 账户权限 self.trycount = 0 # 登录尝试次数 self.isdel = 0 # 用户删除标识 # 随机验证码逻辑有误 self.code = my_Common.verification_code(1) # 随机验证码 # 将json字符串一次性读入json字典中 self.dict_user = {} self.db_load()
def modify_user_info(self): """ 打印用户信息 :return: 用户信息字符串 """ if self.islocked == 1: currstatus = "账户锁定" else: currstatus = "账户正常" frmuser = my_template.user_info.format( username=self.username, name=self.name, mobile=self.mobile, bindcard=self.bindcard, role=self.role, islocked="是" if self.islocked == 1 else "否", isdel="是" if self.isdel == 1 else "否" ) # 打印用户信息 my_Common.show_message(frmuser, "NOTICE") # 开始修改 my_Common.show_message("请输入新的资料,若不更新直接回车:", "NOTICE") # 三元运算 new_name = input("姓名({0}); ".format(self.name)) new_mobile = input("手机({0}): ".format(self.mobile)) self.name = self.name if len(new_name) == 0 else new_name self.mobile = self.mobile if len(new_mobile) == 0 else new_mobile # 更新用户资料库变量 self.dict_user[self.username]["name"] = self.name self.dict_user[self.username]["mobile"] = self.mobile if self.update_user(): my_Common.show_message("信息更新成功!", "NOTICE") else: my_Common.show_message("更新失败,查看日志!", "ERROR")
def setUp(self): self.common = Common()
class CommonTest(unittest.TestCase): ''' Initialize ''' def setUp(self): self.common = Common() ''' Test MIME type from the file ''' def test_readMime(self): # Initialize file = "artifacts/css-cheat-sheet-v1.png" # Assert self.assertEqual("image/png", self.common.readMime(file)) ''' Test for valid folder when output is True ''' def test_validateFolderTrue(self): # Initialize current = os.getcwd() folder = os.path.join(current, "tests/artifacts") # Execute status = self.common.validateFolder(folder) # Assert self.assertTrue(status) # Cleanup self.common.changeFolder(current) ''' Test for valid folder when output is False ''' def test_validateFolderFalse(self): # Initialize current = os.getcwd() folder = os.path.join(current, "tests/arti") # Execute status = self.common.validateFolder(folder) # Assert self.assertFalse(status) # Cleanup self.common.changeFolder(current) ''' Test folder name from the MIME type ''' def test_getFolderName(self): # Initialize mime = self.common.readMime("artifacts/css-cheat-sheet-v1.png") # Assert self.assertEqual("Image/Png", self.common.getFolderName(mime)) ''' Test chaning to user's supplied folder ''' def test_changeFolder(self): # Initialize current = os.getcwd() folder = os.path.join(current, "tests/artifacts") # Execute self.common.changeFolder(folder) # Assert self.assertEqual(os.getcwd(), folder) # Cleanup self.common.changeFolder(current) ''' Test create folder if not already exists ''' def test_createFolder(self): # Initialize current = os.getcwd() folder = os.path.join(current, "tests/artifacts/tmp") # Execute self.common.createFolder(folder) status = os.path.isdir(folder) & os.path.exists(folder) # Assert self.assertTrue(status) # Cleanup os.rmdir(folder) ''' Test moving files to the newly created folder ''' def test_moveFileToFolder(self): # Initialize current = os.getcwd() parent = os.path.join(current, "tests/artifacts") folder = os.path.join(parent, "tmp") file = "css-cheat-sheet-v1.png" newfile = "css-cheat-sheet-v1-new.png" # Execute self.common.changeFolder(parent) copyfile(file, newfile) self.common.createFolder(folder) self.common.moveFileToFolder(folder, newfile) status = os.path.isfile(os.path.join(folder, newfile)) # Assert self.assertTrue(status) # Cleanup os.remove(os.path.join(folder, newfile)) os.rmdir(folder) self.common.changeFolder(current) ''' Test folder's permission when output is True ''' def test_checkFolderPermissionTrue(self): # Initialize folder = os.path.join(os.getcwd(), "tests/artifacts") # Execute status = self.common.checkFolderPermission(folder) # Assert self.assertTrue(status) ''' Check folder's permission when output is False ''' def test_checkFolderPermissionFalse(self): # Initialize folder = "/etc/apache2/extra" # Execute status = self.common.checkFolderPermission(folder) # Assert self.assertFalse(status)
def login(self): """ 用户登录过程函数,输入用户名和密码后调用内部方法 _user_login进行登录验证 :return: """ # 如果大于最大尝试次数 while self.trycount <= my_conf.ERROR_MAX_COUNT: if (self.trycount == my_conf.ERROR_MAX_COUNT - 1): my_Common.show_message('请注意再输入一次系统将锁定当前用户', "NOTICE") self.username = input("用户名: ") password = input("密 码: ") self.code = '1' # my_Common.verification_code(1) #随机验证码 # my_Common.show_message("验证码:{0}".format(self.code), "INFORMATION") check_code = '1' # input("请输入验证码:") ''' 验证码 ''' if check_code != self.code: my_Common.show_message("验证码错误!", "ERROR") continue ''' 用户名不存在 类中 @property 的方法 ''' if not self.user_exists: my_Common.show_message("用户名/密码错误!", "ERROR") continue # 调用用户登录方法进行登录,登录成功后更新对象self self._user_login(password, check_code) # 用户锁定就直接退出 if self.islocked: my_Common.show_message("该用户已被锁定,请联系系统管理员!", "ERROR") self.trycount = 0 break # 登录成功 退出登录 if self.islogin: break else: my_Common.show_message("用户名密码错误", "NOTICE") # else: if self.trycount > my_conf.ERROR_MAX_COUNT: # 失败后锁定 self.islocked = 1 # 更新用户信息 self.dict_user[self.username]["islocked"] = self.islocked self.update_user() my_Common.show_message("输入错误次数过多,请联系系统管理员!", "ERROR")
class FileOrganizerTest(unittest.TestCase): ''' Initialize ''' def setUp(self): self.fileOrganizer = FileOrganizer() self.common = Common() ''' Test Folder validation when output is True ''' def test_validateFolderTrue(self): # Initialize current = os.getcwd() folder = os.path.join(current, "tests/artifacts") self.fileOrganizer.currentFolder = folder # Execute status = self.fileOrganizer.validateFolder() # Assert self.assertTrue(status) # Cleanup self.common.changeFolder(current) ''' Test Folder validation when output is False ''' def test_validateFolderFalse(self): # Initialize current = os.getcwd() folder = os.path.join(current, "tests/arti") self.fileOrganizer.currentFolder = folder # Execute status = self.fileOrganizer.validateFolder() # Assert self.assertFalse(status) # Cleanup self.common.changeFolder(current) ''' Test folder's permission when output is True ''' def test_folderPermissionTrue(self): # Initialize current = os.getcwd() folder = os.path.join(current, "tests/artifacts") self.fileOrganizer.currentFolder = folder # Execute status = self.fileOrganizer.folderPermission() # Assert self.assertTrue(status) ''' Check folder's permission when output is False ''' def test_folderPermissionFalse(self): # Initialize folder = "/etc/apache2/extra" self.fileOrganizer.currentFolder = folder # Execute status = self.fileOrganizer.folderPermission() # Assert self.assertFalse(status) ''' Test fetching all the files from the folder ''' def test_fetchFiles(self): # Initialize current = os.getcwd() folder = os.path.join(current, "tests/artifacts") # Execute self.common.changeFolder(folder) self.fileOrganizer.fetchFiles() # Assert self.assertEqual(2, len(self.fileOrganizer.currentFiles)) # Cleanup self.common.changeFolder(current) ''' Test organizing files when folder is empty ''' def test_organizeFilesEmpty(self): # Initialize self.fileOrganizer.currentFiles = [] # Execute status = self.fileOrganizer.organizeFiles() # Assert self.assertFalse(status)
def setUp(self): self.fileOrganizer = FileOrganizer() self.common = Common()
initdb = my_init_DB() today = datetime.now().strftime("%Y-%m-%d") weekoftoday = date.weekday(datetime.now()) # 用户初始化 curruser = my_clsUsers() # --------- 开始 主程序 -------------- exitFlag = False while not exitFlag: # 根据是否登录显示不同的登录界面 if not curruser.islogin: print( my_template.index_default_menu.format( "欢迎您,请登录", today, my_Common.numtochr(weekoftoday))) else: print( my_template.index_logined_menu.format( "欢迎您: {0}".format(curruser.name), today, my_Common.numtochr(weekoftoday))) choose = my_Common.input_msg("选择功能编号[1-3]: ", ("1", "2", "3")).strip() # 3 退出系统 if choose == "3": exitFlag = True continue # 2 用户登录 if choose == "1":
def __init__(self): self.common = Common() self.currentFolder = '' self.currentFiles = ''
class FileOrganizer: ''' Initialize variables ''' def __init__(self): self.common = Common() self.currentFolder = '' self.currentFiles = '' ''' Start ''' def main(self, folder): self.initialize(folder) if (self.validateFolder()): if (self.folderPermission()): self.fetchFiles() self.organizeFiles() ''' Initialize the program ''' def initialize(self, folder): self.currentFolder = folder if folder != "" else self.fetchInput() ''' Request user for the name of the folder ''' def fetchInput(self): try: folder = self.common.rawInput("Enter folder to organize: ") except: folder = '' return folder ''' Validate Folder ''' def validateFolder(self): return self.common.validateFolder(self.currentFolder) ''' Check for folder's permission ''' def folderPermission(self): return self.common.checkFolderPermission(self.currentFolder) ''' Fetch all the files from the folder and store them in list ''' def fetchFiles(self): print("Fetching all files from %s" % (os.getcwd())) for root, dirs, files in os.walk(os.getcwd()): self.currentFiles = [f for f in files if not f[0] == '.'] break ''' Organize files into folders and sub-folders ''' def organizeFiles(self): if (len(self.currentFiles) == 0): print("Folder is empty. No files to organize, exiting.") return False else: print("Organizing files into sub-folders.") try: for file in self.currentFiles: print("") folder = self.common.getFolderName( self.common.readMime(file)) self.common.createFolder(folder) self.common.moveFileToFolder(folder, file) except: print("Exception occured") return False finally: print("Process completed.") return True