zoukankan      html  css  js  c++  java
  • 项目一:ATM+购物车

    三层架构版(做了优化,添加了管理员)

    源码:https://gitee.com/FenYiYuan/python.git
    

    项目要求:
    登录,注册,查看余额,转账,存款,取款,查看流水,购物,查看购买商品,退出,锁定

    import os, time, datetime
    
    class Util:
        def checkuser(self, name):
            flag = 0
            userpwd = ""
            money = ''
            if os.path.exists("db.txt"):
                with open("db.txt", mode="rt", encoding="utf-8") as f:
                    for line in f:
                        username, userpwd, money = line.strip().split(":")
                        if name == username:
                            flag = 1
                            break
            return flag, userpwd, money
    
        def changeusermsg(self, name, money):
            with open("db.txt", mode='rt', encoding="utf-8") as f, 
                    open("db.txt.swap", mode="wt", encoding="utf-8") as ff:
                for line in f:
                    uname, upwd, umoney = line.strip().split(":")
                    if uname == name:
                        umoney = round(eval(umoney+money),2)
                        ff.write(f'{uname}:{upwd}:{umoney}
    ')
                    else:
                        ff.write(f'{uname}:{upwd}:{umoney}
    ')
            os.remove("db.txt")
            os.rename("db.txt.swap", "db.txt")
            return
    
        def nowtime(self):
            return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    
        def water(self, wstr, uname, money):
            nowtime = self.nowtime()
            with open(f'{uname}.log', mode="at", encoding="utf-8") as f:
                f.write(f'{nowtime}  {wstr}  {money}¥
    ')
            return
    
        def shopmsg(self, uname, shoplist, sum):
            shoptime = self.nowtime()
            with open(f'{uname}.shop', mode='at', encoding="utf-8") as f:
                f.write(f'{shoptime}
    ')
                for k, v in shoplist.items():
                    f.write(f'商品名:{dic_shop.get(k)[0]}  单价:{dic_shop.get(k)[1]}¥  数量:{v}
    ')
                f.write(f'总额:{sum}¥
    ')
            return
    
        def readwater_or_shopmsg(self, path):
            if os.path.exists(path):
                with open(path, mode="rt", encoding="utf-8") as f:
                    for line in f:
                        print(line, end="")
                return 1
            else:
                return 0
    
        def is_input_lgc(self, s, num):
            if num == 1:
                for i in s:
                    if not i.isalpha():
                        print("账号存在非法字符")
                        return 0
                if 2 < len(s) < 8:
                    return 1
                else:
                    print("非法账号")
                    return 0
            elif num == 2:
                if s.isdigit():
                    return 1
                else:
                    for i in s:
                        if i.isdigit() or i == '.':
                            continue
                        else:
                            return 0
                    if s.count('.') == 1 and len(s[s.find('.') + 1:]) <= 2:
                        return 1
                    else:
                        return 0
            else:
                for i in s:
                    if i.isspace():
                        print("密码中存在空格")
                        return 0
                return 1
    class Lock:
        def locked(self, name):
            locktime = str(time.time())
            with open("lock.txt", mode="at", encoding="utf-8") as f:
                f.write(f'{name}:{locktime}
    ')
    
        def checklock(self, name):
            flag = 0
            if os.path.exists('lock.txt'):
                with open("lock.txt", mode="rt", encoding="utf-8") as f:
                    for i in f:
                        username, _= i.strip().split(":")
                        if username == name:
                            flag =1
            return flag
    
        def unlock(self, name):
            with open("lock.txt", mode="rt", encoding="utf-8") as f:
                for line in f:
                    username, locktime = line.strip().split(":")
                    if username == name:
                        break
            curtime = datetime.datetime.now()
            lock_time = datetime.datetime.fromtimestamp(float(locktime))
            difftime = (curtime - lock_time).seconds
            if difftime < 60:
                return 60 - int(difftime)
            else:
                with open("lock.txt", mode="rt", encoding="utf-8") as f,
                        open("lock.txt.swap", mode="wt", encoding="utf-8") as ff:
                    for i in f:
                        username, locktime = i.split(":")
                        if username == name:
                            continue
                        else:
                            ff.write(f'{username}:{locktime}')
                os.remove("lock.txt")
                os.rename('lock.txt.swap', 'lock.txt')
                return 0
    
    class Atm(Util):
        def view_account(self):
            '''查看余额'''
            print(f"{cookie}的余额".center(50, '='))
            *_, money = self.checkuser(cookie)
            print(f"余额:{money}¥")
            return
    
        def transfer_accounts(self):
            '''转账'''
            print('转账'.center(50, '='))
            tname = input("请输入要转账的账号:").strip()
            flag, *_ = self.checkuser(tname)
            if flag:
                *_, money = self.checkuser(cookie)
                while 1:
                    tmoney = input("请输入转账金额:").strip()
                    if not self.is_input_lgc(tmoney, 2):
                        print("非法输入,请重新输入")
                        continue
                    if float(tmoney) > float(money):
                        print("账号余额不足, 无法转账")
                        continue
                    break
                self.changeusermsg(cookie, f'-{tmoney}')
                time.sleep(0.5)
                self.changeusermsg(tname, f'+{tmoney}')
                print("转账成功".center(50, '='))
                self.water(f"转账({tname})", cookie, f'-{tmoney}')
                self.water(f"({cookie})转账", tname, f'+{tmoney}')
                return
            else:
                print("转账账号不存在")
                return
    
        def withdrawal(self):
            '''存款'''
            print("存款".center(50, '='))
            while 1:
                wmoney = input("请输入存款金额:").strip()
                if not self.is_input_lgc(wmoney, 2):
                    print("非法输入,请重新输入")
                    continue
                break
            self.changeusermsg(cookie, f'+{wmoney}')
            print("存款成功".center(50, '='))
            self.water("存款", cookie, f'+{wmoney}')
            return
    
        def deposit(self):
            '''取款'''
            print("取款".center(50, '='))
            *_, money = self.checkuser(cookie)
            while 1:
                dmoney = input("请输入取款金额:").strip()
                if not self.is_input_lgc(dmoney, 2):
                    print("非法输入,请重新输入")
                    continue
                if float(money) < float(dmoney):
                    print("余额不足")
                    continue
                break
            self.changeusermsg(cookie, f'-{dmoney}')
            print("取款成功".center(50, '='))
            self.water("取款", cookie, f'-{dmoney}')
            return
    
        def check_water(self):
            '''查看流水'''
            print(f'{cookie}的流水'.center(50, '='))
            flag = self.readwater_or_shopmsg(f'{cookie}.log')
            if not flag:
                print("您没有流水可以查看")
                return
            return
    
    class Shop(Util):
        def shopping(self):
            '''购物'''
            print("购物".center(50, '='))
            for k, v in dic_shop.items():
                print(f'  {k}. {v[0]}  {v[1]}¥')
            print(f'  (购物请输入商品序号, 结算请输入Y / y)')
            sum = 0
            shop_car = {}
            while 1:
                shopcmd = input("请输入命令(序号)>>>:")
                if shopcmd.upper() == "Y":
                    for k, v in shop_car.items():
                        sum += dic_shop.get(k)[1] * int(v)
                    *_, money = self.checkuser(cookie)
                    if float(money) >= sum:
                        self.changeusermsg(cookie, f'-{sum}')
                        self.water("购物", cookie, f'-{sum}')
                        print("购物成功".center(50, '='))
                        self.shopmsg(cookie, shop_car, sum)
                        return
                    else:
                        print("账号余额不足,购物失败")
                        return
                if shopcmd in dic_shop:
                    shopcount = input("请输入购买数量:")
                    shop_car[shopcmd] = shopcount
                else:
                    print("无效指令,请重新输入")
    
        def check_shop(self):
            '''查看购买商品'''
            print(f'{cookie}的购物历史'.center(50, '='))
            flag = self.readwater_or_shopmsg(f'{cookie}.shop')
            if not flag:
                print("您还没有购物历史哦!")
                return
            return
    
    class User(Atm, Shop, Util, Lock):
        def login(self):
            print("登录界面".center(50, '='))
            name = input("请输入账号:").strip()
            flag, userpwd, _ = self.checkuser(name)
            if flag:
                if self.checklock(name):
                    res = self.unlock(name)
                    if res:
                        print(f'账号{res}秒后解锁')
                        return
                count = 0
                while 1:
                    pwd = input("请输入密码:").strip()
                    if pwd == userpwd:
                        global cookie
                        cookie = name
                        break
                    else:
                        count += 1
                        if count == 3:
                            self.locked(name)
                            print("账号输入次数过多,锁定1分钟")
                            return
                        print("密码错误,请从新输入")
                while 1:
                        print(f"欢迎您{name}".center(50, '='))
                        print(msg1)
                        cmd = input("请输入命令(序号)>>>:")
                        if not cmd.isdigit() or int(cmd) > 7:
                            print("命令无效,请重新输入")
                            continue
                        if cmd == "0":
                            self.exit()
                            return
                        else:
                           self.__getattribute__(dic.get(str(int(cmd)+2))[0])()
            else:
                print("账号不存在,请先注册")
                return
    
        def regist(self):
            print("注册界面".center(50, '='))
            print(msg2)
            while 1:
                name = input("请输入账号:").strip()
                if self.is_input_lgc(name, 1):
                    flag, *_ = self.checkuser(name)
                    if not flag:
                        break
                    else:
                        print("账号已存在")
            while 1:
                pwd = input("请输入密码:").strip()
                if not self.is_input_lgc(pwd, 3):
                    continue
                if len(pwd) < 4:
                    print("密码长度小于4")
                    continue
                check_pwd = input("请确认密码:").strip()
                if check_pwd == pwd:
                    break
                print("两次密码不一致")
    
            while 1:
                money = input("请输入账号金额:").strip()
                if self.is_input_lgc(money, 2):
                    break
                print("金额非法输入,请重新注册")
    
            with open("db.txt", mode="at", encoding="utf-8") as f:
                f.write(f'{name}:{pwd}:{money}
    ')
            print("注册成功".center(50, '='))
            return
    
        def exit(self):
            print("Bye".center(50, "="))
            global cookie
            cookie = ''
    
    cookie = ''
    dic = {'0':('exit','退出'),'1':('login','登录'), '2':('regist','注册'),
           '3':('view_account','查看余额'), '4':('transfer_accounts','转账'),'5':('withdrawal','存款'),
           '6':('deposit','取款'), '7':('check_water','查看流水'),'8':('shopping','购物'),
           '9':('check_shop','查看购买商品')
    }
    
    dic_shop = {
        '1':("thinkpad",8888),
        '2':("小黄书",100),
        '3':("iphone",5500),
        '4':("辣条",2.5),
        '5':("衣服",199),
        '6':("水果",38.8),
    }
    msg1 = '''
        0.退出
        1.查看余额
        2.转账
        3.存款
        4.取款
        5.查看流水
        6.购物
        7.查看购买商品
    '''
    msg2 = '''
        欢迎注册001ATM机账号!注意注册账号请满足以下规则。
        1.账号必须由字母组成,长度大于2小于8
        2.密码中不允许有空格,长度大于等于4
        3.账号金额必须是整数或小数(小数点后只允许2位)
        '''
    
    if __name__ == '__main__':
        print("欢迎使用001ATM机!".center(50, '='))
        while 1:
            for i in range(1, 3):
                print(f'  {i}. {dic.get(str(i))[1]}')
            cmd = input("输入指令(序号)>>>:").strip()
            if cmd in dic:
                if cmd == '1' or cmd == '2':
                    o = User()
                    res = o.__getattribute__(dic.get(cmd)[0])
                    res()
                else:
                    print("======>请先登录")
                    continue
            else:
                print("无效命令")
    
    
  • 相关阅读:
    python3之Django内置模板标签和过滤器
    JavaScript(1)
    python3之Django基础篇
    CSS
    HTML
    python3之SQLAlchemy
    python3之memcached
    web服务器-nginx虚拟主机
    web服务器-nginx默认网站
    web服务器-Nginx下载限速
  • 原文地址:https://www.cnblogs.com/chenwenyin/p/12515967.html
Copyright © 2011-2022 走看看