def create_teacher(self): name, school =self.create_method() # 输入讲师的姓名, 输入讲师的密码, 将老师的信息写入user_account teacher_obj = Teacher(name) teacher_obj.school = school self.teacher_pickle_obj.dump(teacher_obj) print_log('创建成功', 'info') return
def main(): """ 打印欢迎信息 login: 得到的返回值,用户姓名和身份 :return: """ print_log('欢迎登陆选课系统', 'info') ret = login() # 登陆 #ret = {'username':'******','role':'Manager'} ret['role'] = ret['role'].strip('\n') if ret: print(ret['username'], ret['role']) role_class = getattr(sys.modules[__name__], ret['role']) # 得到 类名 if ret['role'] == 'Management': obj = role_class(ret['username']) # 得到基本的角色对象 ,我想直接从数据库得道实例 elif ret['role'] == 'Teacher': obj = Role.getObj(ret['username'], teacher_obj) else: clas_name = input("你是学生账号,请输入你所在的班级>>:").strip() stu_path = path.join(studentinfo, clas_name) obj = Role.getObj(ret['username'], stu_path) while True: for i, j in enumerate(role_class.menu, 1): print('\033[32;1m%s %s\033[0m' % (i, j[0])) ret = int(input('请输入操作序号')) if role_class.menu[ret - 1][1] == 'exit': exit('退出系统') else: getattr(obj, role_class.menu[ret - 1][1])()
def manage_main(user_data): """ 管理主程序 :param user_info: 是个人信息字典 :return: """ adm_menu = u""" -------Administrator interface --------- 1.Add new account 2.Lock account 3.Unlock account 4.Logout """ menu_dic = { '1': add_acc, '2': lock_acc, '3': unlock_acc, '4': logout, } # exit_flag = False while not exit_flag: util.print_log(adm_menu, 'info') user_option = input('please input your choice>> ').strip() if user_option in menu_dic: menu_dic[user_option]() else: util.print_log('input the wrong choice, please try again', 'error') # manage_main()
def print_good_balance(name, total_consume, shop_cart): user_shop_info = u""" -------welcom %s --------- 1. Total consume:%s 2. Product you have bought:%s """ % (name, total_consume, shop_cart) util.print_log(user_shop_info, 'info')
def show_student(self): # 查看学生列表 if self.clas: path = self.clas.student_path load_info = Mypickle(path).loaditer() for item_info in load_info: for i in item_info.__dict__.keys(): if i != 'clas' and i != 'budget': print(i, item_info.__dict__[i]) print('-' * 50) else: print_log('你没有绑定任何班级')
def bound_school(self,school,**kwargs): key = list(kwargs.keys())[0] value= kwargs[key] school_info = self.school_pickle_obj.loaditer() # 生成器 for school_obj in school_info: # 一条记录就是一个对象, class_info 有很多对象 if school_obj.__dict__['name'] == school: school_obj.__dict__[key].append(value) school_obj1 = school_obj print(school_obj1.name,school_obj1.course) self.school_pickle_obj.edit(school_obj1) print_log('绑定学校成功','info')
def account_info(user_data): """ 打印用户信息 :param user_info: :return: """ # user_info = db_handler.load_file(user_data['account_name']) user_info = user_data['account_data'] print('ACCOUNT INFO'.center(50, '-')) for k, v in user_info.items(): # ??? if k not in ('password',): util.print_log('%15s: %s' % (k, v), 'info') print('END'.center(50, '-'))
def create_student(self): name, school =self.create_method() # 输入的学生姓名,密码, 将信息写入user_account choose_course = input('请输入要学习的课程>>:').strip() choose_class = input('请输入所在的班级>>:').strip() # class_objs = self.class_pickle_obj.loaditer() for clas in class_objs: #这里可以优化 if clas.name == choose_class: stu_obj = Student(name) stu_obj.school = school stu_obj.clas = clas stu_obj.course = choose_course Mypickle(clas.student_path).dump(stu_obj) print_log('创建成功', 'info')
def modify_score(self): # 修改学生成绩 student_name = input('输入要修改成绩的学生姓名>>:').strip() student_score = input('输入成绩>>:').strip() if self.clas: stu_path = self.clas.student_path load_info = Mypickle(stu_path).loaditer() # 加载的是学生对象 for item_info in load_info: if item_info.__dict__['name'] == student_name: item_info.__dict__['score'] = student_score Mypickle(stu_path).edit(item_info) # 保存的是学生对象 else: print_log('你输入的学生不在该班级', 'error') else: print_log('你还没有绑定班级', 'error')
def create_classes(self): self.show_school() school = input('请输入学校>>:').strip() school_obj = Role.getObj(school, schoolinfo) #学校对象 print('你所在学校的可选课程>>:%s ' % school_obj.course) course_name = input('请输入课程名称>>:').strip() class_name = input('请输入班级名称:').strip() student_path = path.join(studentinfo, class_name) open(student_path, 'w').close() class_obj = Classes(class_name, course_name, student_path) self.class_pickle_obj.dump(class_obj) school_obj.clas.append(class_obj.name) self.school_pickle_obj.edit(school_obj) print_log('创建成功', 'info')
def load_file(account): """ :param account: :return: user_info :用户信息读到内存 """ # user_info = {} #可以不需要提前定义 file_name = '%s/account/%s.json' % (settings.BASE_DIR, account) if os.path.isfile(file_name): with open(file_name, 'r', encoding='utf-8') as f: user_info = json.load(f) return user_info else: util.print_log('there is no account info for %s' % account, 'error') exit()
def boundClass(self): # 默认管理员会设置班级, 但是可以自己选 班级 print('你目前所在的班级>>:%s' % self.clas.name) previous_clas = self.clas super().boundClass() stu_path = path.join(studentinfo, self.clas.name) stu_path1 = path.join(studentinfo, previous_clas.name) Mypickle(stu_path).dump(self) # 把一个新对象加入到文件 Mypickle(stu_path1).delInfo(self) #在原来班级信息中删除学生信息 print_log('绑定班级成功', 'info') # load_info = Mypickle(course_obj).loaditer() # for item_info in load_info: # for i in item_info.__dict__.keys(): # print(i, item_info.__dict__[i]) # print('-' * 50)
def make_transaction(log_obj, user_info, tran_type, amount, **kwargs): """ 处理所有的用户交易 :param log_obj: log 类型 :param user_info: 用户数据 :param tran_type: 交易类型 :param amount: 交易数额 :param kwargs: 以后扩展 :return: 最新的用户数据 """ amount = float(amount) if tran_type in settings.TRANSACTION_TYPE: interest = amount * settings.TRANSACTION_TYPE[tran_type]['interest'] old_balance = user_info['balance'] #repay if settings.TRANSACTION_TYPE[tran_type]['action'] == 'plus': new_balance = old_balance + amount + interest log_obj.info('account_name:%s,transaction:%s,amount:%s,interest:%s' % (user_info['id'], tran_type, amount, interest)) # withdraw/transfer/consume elif settings.TRANSACTION_TYPE[tran_type]['action'] == 'minus': new_balance = old_balance - amount - interest if new_balance < 0: util.print_log('there is no enough money to pay for the transition[-%s],you current balance is %s' % (amount, old_balance), 'error') save_flag = False new_balance = old_balance return new_balance, save_flag else: if kwargs.get('transfer_name'): #only for transfer transfer_name_info = db_handler.load_file(kwargs.get('transfer_name')) transfer_name_balance = transfer_name_info['balance'] + amount transfer_name_info['balance'] = transfer_name_balance db_handler.update_file(transfer_name_info['id'], transfer_name_info) log_obj.info('account_name:%s,transaction:%s,transfer_name:%s,amount:%s,interest:%s' % ( user_info['id'],tran_type,transfer_name_info['id'], amount, interest)) else: log_obj.info('account_name:%s,transaction:%s,amount:%s,interest:%s' % ( user_info['id'], tran_type, amount, interest)) user_info['balance'] = new_balance main.user_data['account_data'] = user_info save_flag = db_handler.update_file(user_info['id'], user_info) #数据保存成功 return user_info, save_flag else: util.print_log('there is no %s transition type', tran_type)
def lock_or_not(lock_flag): exit_flag = False while not exit_flag: acc_name = input('input the account you want to locked>>').strip() if acc_name == 'b': exit_flg = True else: accout_file = '%s/account/%s.json' % (settings.BASE_DIR, acc_name) if os.path.isfile(accout_file): acc_dic = db_handler.load_file(acc_name) if lock_flag == 1: #lock acc_dic['status'] = 1 #lock else: acc_dic['status'] = 0 #unlock db_handler.update_file(acc_dic['id'], acc_dic) return else: util.print_log('%s does not exist, please double check', 'error')
def login(): """ 登陆函数 :return: """ retry_count = 0 while retry_count < 3: account = input('please input your account->').strip() password = input('please input your password->').strip() with open(user_account) as f: for line in f: user, pwd, role = line.split('|') if account == user and password == pwd: print_log('登陆成功', 'info') return {"username": user, 'role': role} retry_count += 1 else: print_log("[%s]账户太多次尝试" % account) # log_obj.error("[%s]账户太多次尝试" % account) # log type exit()
def pay_check(user_data): """ pay_check :param user_data: :return: """ count = 0 exit_flag = False user_name = user_data['account_name'] log_name = '%s/log/%s.log' % (settings.BASE_DIR, user_name) while not exit_flag: search_mon = input('please input the month of the log you want to search, "example = 2018-01",' ' or input "b" to quit >>:').strip() if search_mon == 'b': return else: if os.path.isfile(log_name): with open(log_name, 'r') as f: for line in f: search_res = re.match(search_mon, line) if search_res: util.print_log(line, 'info') count += 1 util.print_log('Above are the consume log, total %s' % count, 'info') else: util.print_log('there is no consume log', 'error') exit_flag = True
def shopping(name, log_obj): user_shop_cart = load_shop_cart() # 所有用户的字典信息 product_list = load_product() # 所有货物清单 shop_cart = [] consume_amount = 0 exit_flag1 = False while not exit_flag1: good_num = [] #用来存商品名 for index, k in enumerate(product_list): good_num.append(k) util.print_log("%s:%s-->price:%s" % (index, k, product_list[k]), 'info') num = input( 'if you want buy anything, input the good number, or input "b">>:' ).strip() if num.isdigit(): # 判断是否是数字 num = int(num) if 0 <= num <= len(product_list): selected_good = good_num[num] good_price = product_list[selected_good] shop_cart.append(selected_good) user_shop_cart[name]['shop_cart'].append(selected_good) consume_amount = float(consume_amount) + float( good_price) #总共消费的金额 util.print_log( 'you have choose %s, and the total money is %s' % (shop_cart, consume_amount), 'info') elif num.lower() == 'b': # exit_flag1 = True print_good_balance(name, consume_amount, shop_cart) log_obj.info( 'account_name:%s, have bought %s,and the total cost:%s' % (name, shop_cart, consume_amount)) dump_account(user_shop_cart) return consume_amount else: print('The good does not exist')
def add_acc(*args): """ :return: """ user_shop_cart = shopping_mall.load_shop_cart() acc_dic = { 'id': 1234, 'password': '******', 'credit': 15000, 'balance': 15000, 'enroll_date': '2016-01-02', 'expire_date': '2021-01-01', # 自动开卡日期+5年 'pay_day': 22, 'status': 0, # 0 = normal, 1 = locked, 2 = disabled 'admin_flag': 0 # 0 = not admin, 1 = admin } user_data1 = {'account_data': None} exit_flag = False while not exit_flag: acc_name = input('please input name>>').strip() accout_file = '%s/account/%s.json' % (settings.BASE_DIR, acc_name) if os.path.isfile(accout_file): util.print_log( 'the account %s has been existed, please use a new name' % acc_name, 'error') return else: password = input('please input more than 3 digists>>').strip() if len(password) > 3 and password.isdigit(): acc_dic['id'] = acc_name acc_dic['password'] = util.passwd_md5(acc_name, password) current_date = datetime.datetime.now() #注册日期 expire_date = current_date + datetime.timedelta(1095) #到期日 pay_day = current_date + datetime.timedelta(50) #还款日期 acc_dic['enroll_date'] = current_date.strftime( '%Y-%m-%d') #2016-01-02 acc_dic['expire_date'] = expire_date.strftime('%Y-%m-%d') acc_dic['pay_day'] = pay_day.day db_handler.update_file(acc_dic['id'], acc_dic) util.print_log('%s account has been created' % acc_name, 'info') user_data1['account_data'] = acc_dic main.account_info(user_data1) new_acc_dic = {'shop_cart': []} user_shop_cart[acc_name] = new_acc_dic shopping_mall.dump_account(user_shop_cart) exit_flag = True elif acc_name == 'b' or password == 'b': # exit_flag = True return else: util.print_log( 'please input the name and password again, the password should be more than 3', 'error')
def access_auth(account, password): """ :param account: :param password: :return: account_data """ db_path = '%s/account' % settings.BASE_DIR print(db_path) account_file = '%s/%s.json' % (db_path, account) if os.path.isfile(account_file): account_data = db_handler.load_file(account) if account_data['status'] == 1: # the account is locked util.print_log('your account has been locked, please contact the administrator', 'error') option = input('please press b to quit') if option == 'b': exit('quit the system') if account_data['status'] == 0: password_md5 = util.passwd_md5(account, password) if password_md5 == account_data['password']: expire_time = time.mktime(time.strptime(account_data['expire_date'],'%Y-%m-%d')) if time.time() > expire_time: util.print_log('the account %s has been expired, please contact the bank' % account, 'error') exit() else: util.print_log('welcome %s \o/'%account,'info') main.access_logger.info('%s access the ATM successfully' % account) return account_data else: util.print_log('the password of the account %s is not right' % account, 'error') else: util.print_log('there is no any information of %s' % account, 'error') exit()
def user_interface(account_data): """ #用户交互函数 interact with user: :return: """ menu = u""" -------Bank interface --------- 1.account_info 2. repay 3. withdraw 4. transfer 5. consume 6. pay_check 7. logout """ menu1 = u""" -------Bank interface --------- 1. account_info 2. repay 3. withdraw 4. transfer 5. consume 6. pay_check 7. logout 8. Administrator """ menu_dic = { '1': account_info, '2': repay, '3': withdraw, '4': transfer, '5': consume, '6': pay_check, '7': logout, } # 函数字典, 实际上每个选项对应一个函数 admin_flag = account_data['admin_flag'] exit_flag = False while not exit_flag: if admin_flag == 1: # 管理员 util.print_log(menu1, 'info') menu_dic['8'] = manage.manage_main else: util.print_log(menu,'info') user_option = input('>>:').strip() if user_option == 'b': return if user_option in menu_dic: menu_dic[user_option](user_data) else: util.print_log('your choice does not exist', 'error')
def com_tran_module(user_data, tran_type): """ 交易交互模块 :param user_data: :return: user_info , and back_flag """ user_info = db_handler.load_file(user_data['account_name'])#user_data 全局变量 balance_info = ''' --------- bank info -------- credit: %s balance: %s''' % (user_info['credit'], user_info['balance']) util.print_log(balance_info, 'info') back_flag = False while not back_flag: if tran_type in settings.TRANSACTION_TYPE: amount = input('please input the transaction amount>>:').strip() if len(amount)>0 and amount.isdigit(): amount = float(amount) if tran_type == 'transfer': transfer_name1 = input('please input the account you want to transfer>>:').strip() if transfer_name1 == 'b' or amount == 'b': return file_name = '%s/account/%s.json' % (settings.BASE_DIR, transfer_name1) if os.path.isfile(file_name): new_balance, save_flag = transaction.make_transaction(trans_logger, user_info, tran_type, amount, transfer_name = transfer_name1) else: new_balance, save_flag = transaction.make_transaction(trans_logger, user_info, tran_type, amount) if save_flag: util.print_log('transaction successfully', 'info') util.print_log('current balance>>%s' % new_balance['balance'], 'info') else: util.print_log('there is some thing wrong and the transaction is not success', 'error') elif amount == 'b': back_flag = True
def boundClass(self): print('当前绑定的班级>>:%s' % self.clas) super().boundClass() Mypickle(teacher_obj).edit(self) print_log('绑定班级成功', 'info')