import shelve import time class UserData(object): """13-4. 用户注册.""" def __init__(self, fn): self.op = shelve.open(fn) def __del__(self): self.op.close() def register(self): nm = self.cmdInput('UserName:') if self.isExit(nm): print('Username"%s"have been exited' % nm) return False pwd = self.cmdInput('Passward:') c_pwd = self.cmdInput('Confirm:') if pwd != c_pwd: print('Passward not match!') return False self.op[nm] = [pwd] print('Register new user successfully!') def login(self): nm = self.cmdInput('UserName:') if not self.isExit(nm): print('Username"%s"not exited!' % nm) return False pwd = self.cmdInput('Passward:') if pwd == self.op[nm][0]: if len(self.op[nm]) < 2: List = self.op[nm] List.append(self.timer()) self.op[nm] = List print('Welcome Login!') return if self.checkLoginTime(nm): print('Welcome Back!you already login time:%s.' \ % (time.ctime(self.op[nm][1]) )) else: self.op[nm][1] = self.timer() print(time.ctime(self.op[nm][1])) print('Welcome Login!') else: print('Passward incorrect!') def checkLoginTime(self, nm): if (self.timer() - self.op[nm][1]) / 3600 <= 4: return True return False def timer(self): return time.time() def isExit(self, nm): if self.op: for name in self.op.keys(): if nm == name: return True return False def updatePwd(self): nm = self.cmdInput('UserName:') if not self.isExit(nm): return False pwd = self.cmdInput('OriginPassward:') if pwd == self.op[nm][0]: npwd = self.cmdInput('NewPassward:') List = self.op[nm] List[0] = npwd self.op[nm] = List else: print('Origin Passward incorrect!') def cmdInput(self, string, flag=True): try: if True == flag: reciever = input(string).strip() else: reciever = input(string).strip()[0].lower() except(KeyboardInterrupt, SystemExit): reciever = 'Error' print('Abort bymanually!') return reciever def admin(self): enter = self.cmdInput('Delete user info? YES or NO?', False) if 'n' == enter: print(self.op.keys()) elif 'y' == enter: nm = self.cmdInput('Enter user name:') try: self.op.pop(nm) except Exception: print(nm, 'not found!') return def menu(): prompt = ''' --------------------- [R]egister [L]ogin [U]pdatePwd [A]dminstrator --------------------- ''' ud = UserData('DBM') func = { 'r': ud.register, 'l': ud.login, 'u': ud.updatePwd, 'a': ud.admin } while True: enter = ud.cmdInput(prompt, False) if 'Error' == enter: break if enter in 'urla': func[enter]() else: print('choose from ''URLA''') menu()