Python语法进阶(3)- 综合项目实战:抽奖系统
common/consts.py
1 # coding:utf-8 2 3 ROLES=['admin','normal'] 4 FIRSTLEVEL=['level1','level2','level3','level4'] 5 SECONDLEVEL=['level1','level2','level3']
common/error.py
1 # coding:utf-8 2 3 class NotPathError(Exception): 4 def __init__(self,message): 5 self.message=message 6 7 class FormatError(Exception): 8 def __init__(self,message): 9 self.message=message 10 11 class NotFileError(Exception): 12 def __init__(self,message): 13 self.meaage=message 14 15 16 class UserExistsError(Exception): 17 def __init__(self,message): 18 self.message=message 19 20 21 class RoleError(Exception): 22 def __init__(self,message): 23 self.message=message 24 25 26 class LevelError(Exception): 27 def __init__(self,message): 28 self.message=message 29 30 31 class NegativeNumberError(Exception): 32 def __init__(self,message): 33 self.message=message 34 35 class NotUserError(Exception): 36 def __init__(self,message): 37 self.message=message 38 39 40 class UserActiveError(Exception): 41 def __init__(self,message): 42 self.message=message 43 44 45 class CountError(Exception): 46 def __init__(self,message): 47 self.message=message
common/utils.py
1 # coding:utf-8 2 import os 3 import time 4 5 from .error import NotFileError,NotPathError,FormatError 6 7 def timestamp_to_string(timestamp): 8 time_obj=time.localtime(timestamp) 9 time_str=time.strftime('%Y-%m-%d %H:%M:%S',time_obj) 10 return time_str 11 12 def check_file(path): 13 if not os.path.exists(path): 14 raise NotPathError("not found %s" % path) 15 16 if not path.endswith('.json'): 17 raise FormatError("need json format") 18 19 if not os.path.isfile(path): 20 raise NotFileError('this is a not file')
storage/gift.json
{"level1": {"level1": {"糖豆": {"name": "糖豆", "count": 118}}, "level2": {"ipad": {"name": "ipad", "count": 2}}, "level3": {}}, "level2": {"level1": {}, "level2": {}, "level3": {"itouch": {"name": "itouch", "count": 1}}}, "level3": {"level1": {}, "level2": {}, "level3": {}}, "level4": {"level1": {}, "level2": {}, "level3": {}}}
storage/user.json
{"张三": {"username": "张三", "role": "admin", "active": true, "create_time": 1642058199.4055276, "update_time": 1642058199.4055276, "gifts": []}, "张": {"username": "张", "role": "admin", "active": true, "create_time": 1642307860.5210323, "update_time": 1642313986.935938, "gifts": []}, "李四": {"username": "李四", "role": "normal", "active": true, "create_time": 1642313383.1195645, "update_time": 1642313383.1195645, "gifts": ["糖豆", "糖豆", "糖豆", "糖豆", "糖豆", "ipad"]}, "李四2": {"username": "李四2", "role": "admin", "active": true, "create_time": 1642313470.9079525, "update_time": 1642313470.9079525, "gifts": []}, "李四3": {"username": "李四3", "role": "normal", "active": true, "create_time": 1642313498.6640847, "update_time": 1642313498.6640847, "gifts": []}, "王五": {"username": "王五", "role": "normal", "active": true, "create_time": 1642313584.7395563, "update_time": 1642313584.7395563, "gifts": ["糖豆"]}}
admin.py
1 # coding:utf-8 2 import os 3 4 from base import Base 5 from common.error import NotUserError,UserActiveError,RoleError 6 ''' 7 1:admin类的搭建 8 2:获取用户函数(包含获取身份) 9 3:添加用户(判断当前身份是否是管理员) 10 4:冻结与恢复用户 11 5:修改用户身份 12 6:admin的验证(只有admin的用户才能用这个类) 13 7:任何函数都应该动态的更新getuser 14 8:奖品的添加 15 9:奖品的删除 16 10:奖品数量的更新(同步base调整) 17 ''' 18 19 class Admin(Base): 20 def __init__(self,username,user_json,gift_json): 21 self.username=username 22 super().__init__(user_json,gift_json) 23 self.get_user() 24 25 def get_user(self): 26 users=self._Base__read_users() 27 current_user = users.get(self.username) 28 if current_user == None: 29 raise NotUserError('not user %s'% self.username) 30 31 if current_user.get('active') == False: 32 raise UserActiveError('the user %s had not use'% self.username) 33 34 if current_user.get('role') != 'admin': 35 raise RoleError('permission by admin') 36 37 self.user=current_user 38 self.role=current_user.get('role') 39 self.name=current_user.get('username') 40 self.active=current_user.get('active') 41 42 def __check(self,message): 43 self.get_user() 44 if self.role != 'admin': 45 raise Exception(message) 46 47 def add_user(self,username,role): 48 self.__check('permission') 49 self._Base__write_user(username=username,role=role) 50 51 def update_user_active(self,username): 52 self.__check('permission') 53 self._Base__change_active(username=username) 54 55 def update_user_role(self,username,role): 56 self.__check('permission') 57 self._Base__change_role(username,role) 58 59 def add_gift(self,first_level,second_level,gift_name,gift_count): 60 self.__check('permission') 61 self._Base__write_gift(first_level=first_level,second_level=second_level,gift_name=gift_name,gift_count=gift_count) 62 63 def delete_gift(self,first_level,second_level,gift_name): 64 self.__check('permission') 65 self._Base__delete_gift(first_level=first_level,second_level=second_level,gift_name=gift_name) 66 67 def update_gift(self,first_level,second_level,gift_name,gift_count): 68 self.__check('permission') 69 self._Base__gift_update(first_level=first_level,second_level=second_level,gift_name=gift_name,gift_count=gift_count,is_admin=True) 70 71 if __name__=='__main__': 72 store_path=os.getcwd() 73 user_path=os.path.join(store_path,'storage','user.json') 74 gift_path=os.path.join(store_path,'storage','gift.json') 75 admin=Admin('张三',user_path,gift_path) 76 admin.update_gift(first_level='level1',second_level='level1',gift_name='糖豆',gift_count=123)
base.py
1 # coding:utf-8 2 import json 3 import os 4 import time 5 from common.error import UserExistsError,RoleError,LevelError,NegativeNumberError,CountError 6 from common.utils import timestamp_to_string 7 from common.consts import ROLES,FIRSTLEVEL,SECONDLEVEL 8 from common.utils import check_file 9 10 ''' 11 1:导入user.json 文件检查 12 2:导入gift.json 文件检查 13 用户操作 14 1:确定用户表中每个用户的信息字段 15 username 姓名 16 role normal or admin 17 active True or False 18 creat_time timestamp 19 update_time timestamp 20 gifts[] 21 22 username:{username,role,active} 23 2:读取userjson文件 24 3:写入userjson文件(检测用户是否存在),存在则不可写入 25 4:role的修改 26 5:active的修改 27 6:delete_user 28 礼物操作 29 1:gifts 奖品结构的确定 30 2:gifts 奖品的读取 31 3:gifts 添加 32 4:gifts 初始化 33 5:gifts 修改(数量递减) 34 6:gifts 奖品删除 35 { 36 level1:{ 37 level1:{ 38 gift_name1:{ 39 name:xx 40 cout:xx 41 } 42 gift_name2:{} 43 } 44 level2:{} 45 level3:{} 46 } 47 level2:{ 48 level1:{} 49 level2:{} 50 level3:{} 51 } 52 level3:{ 53 level1:{} 54 level2:{} 55 level3:{} 56 } 57 level4:{ 58 level1:{} 59 level2:{} 60 level3:{} 61 } 62 } 63 64 ''' 65 66 class Base(object): 67 def __init__(self,user_json,gift_json): 68 self.user_json = user_json 69 self.gift_json=gift_json 70 self.__check_user_json() 71 self.__check_gift_json() 72 self.__init_gifts() 73 74 def __check_user_json(self): 75 check_file(self.user_json) 76 77 def __check_gift_json(self): 78 check_file(self.gift_json) 79 80 def __read_users(self,time_to_str=False): 81 with open(self.user_json,'r') as f: 82 data=json.loads(f.read()) 83 if time_to_str ==True: 84 for username,v in data.items(): 85 v['create_time']=timestamp_to_string(v['create_time']) 86 v['update_time']=timestamp_to_string(v['update_time']) 87 data[username]=v 88 return data 89 90 def __save(self,data,path): 91 json_data = json.dumps(data,ensure_ascii=False) #json.dumps()方法会默认将其中unicode码以ascii编码的方式输入到string。在json.dumps()方法中加入一个参数,并把值设置为False(默认为True),中文即可正常显示 92 with open(path, 'w') as f: 93 f.write(json_data) 94 95 def __write_user(self,**user): 96 if 'username' not in user: 97 raise ValueError('missing username') 98 if 'role' not in user: 99 raise ValueError('missing role') 100 101 user['active']=True 102 user['create_time']=time.time() 103 user['update_time']=time.time() 104 user['gifts']=[] 105 106 users=self.__read_users() 107 108 if user['username'] in users: 109 raise UserExistsError('username %s had exists'% user['username']) 110 111 users.update( 112 {user['username']:user} 113 ) 114 self.__save(users,self.user_json) 115 116 def __change_role(self,username,role): 117 users = self.__read_users() 118 user=users.get(username) 119 if not user: 120 return False 121 122 if role not in ROLES: 123 raise RoleError('not use role %s' % role) 124 125 user['role']=role 126 user['update_time']=time.time() 127 users[username]=user 128 self.__save(users,self.user_json) 129 return True 130 131 def __change_active(self,username): 132 users = self.__read_users() 133 user=users.get(username) 134 if not user: 135 return False 136 user['active'] = not user['active'] 137 user['update_time']=time.time() 138 users[username] =user 139 140 self.__save(users,self.user_json) 141 return True 142 143 def __delete_user(self,username): 144 users = self.__read_users() 145 user=users.get(username) 146 if not user: 147 return False 148 delete_user= users.pop(username) 149 self.__save(users,self.user_json) 150 return delete_user 151 152 def __read_gifts(self): 153 with open(self.gift_json) as f: 154 data=json.loads(f.read()) 155 return data 156 157 def __init_gifts(self): 158 data={ 159 'level1':{ 160 'level1':{}, 161 'level2':{}, 162 'level3':{} 163 }, 164 'level2': { 165 'level1': {}, 166 'level2': {}, 167 'level3': {} 168 }, 169 'level3': { 170 'level1': {}, 171 'level2': {}, 172 'level3': {} 173 }, 174 'level4': { 175 'level1': {}, 176 'level2': {}, 177 'level3': {} 178 } 179 } 180 gifts = self.__read_gifts() 181 if len(gifts) !=0: 182 return 183 self.__save(data,self.gift_json) 184 185 def __write_gift(self,first_level,second_level,gift_name,gift_count): 186 if first_level not in FIRSTLEVEL: 187 raise LevelError('firstlevel not exists') 188 if second_level not in SECONDLEVEL: 189 raise LevelError('secondlevel not exists') 190 191 gifts=self.__read_gifts() 192 193 current_gift_pool=gifts[first_level] 194 current_sencond_gift_pool=current_gift_pool[second_level] 195 196 if gift_count <=0: 197 gift_count = 1 198 199 if gift_name in current_sencond_gift_pool: 200 current_sencond_gift_pool[gift_name]['count']=current_sencond_gift_pool[gift_name]['count']+gift_count 201 else: 202 current_sencond_gift_pool[gift_name]={ 203 'name':gift_name, 204 'count':gift_count 205 } 206 207 current_gift_pool[second_level]=current_sencond_gift_pool 208 gifts[first_level]=current_gift_pool 209 self.__save(gifts,self.gift_json) 210 211 def __check_and_getgift(self,first_level,second_level,gift_name): 212 if first_level not in FIRSTLEVEL: 213 raise LevelError('firstlevel not exists') 214 if second_level not in SECONDLEVEL: 215 raise LevelError('secondlevel not exists') 216 217 gifts=self.__read_gifts() 218 219 level_one=gifts[first_level] 220 level_two=level_one[second_level] 221 222 if gift_name not in level_two: 223 return False 224 225 return { 226 'level_one':level_one, 227 'level_two':level_two, 228 'gifts':gifts 229 } 230 231 232 def __gift_update(self,first_level,second_level,gift_name,gift_count=1,is_admin=False): 233 data = self.__check_and_getgift(first_level, second_level, gift_name) 234 assert isinstance(gift_count,int),'gift count is a int' 235 if data == False: 236 return data 237 current_gift_pool = data.get('level_one') 238 current_second_gift_pool = data.get('level_two') 239 gifts = data.get('gifts') 240 241 current_gift=current_second_gift_pool[gift_name] 242 243 if is_admin==True: 244 if gift_count<=0: 245 raise CountError('gift count not 0') 246 current_gift['count']=gift_count 247 else: 248 if current_gift['count']-gift_count < 0 : 249 raise NegativeNumberError("gift count can not nagative") 250 current_gift['count']-=gift_count 251 252 current_second_gift_pool[gift_name]=current_gift 253 current_gift_pool[second_level]=current_second_gift_pool 254 gifts[first_level]=current_gift_pool 255 self.__save(gifts,self.gift_json) 256 257 def __delete_gift(self,first_level,second_level,gift_name): 258 data = self.__check_and_getgift(first_level,second_level,gift_name) 259 if data == False: 260 return data 261 current_gift_pool=data.get('level_one') 262 current_second_gift_pool=data.get('level_two') 263 gifts=data.get('gifts') 264 delete_gift_data=current_second_gift_pool.pop(gift_name) 265 current_gift_pool[second_level]=current_second_gift_pool 266 gifts[first_level]=current_gift_pool 267 self.__save(gifts,self.gift_json) 268 return delete_gift_data 269 270 if __name__=='__main__': 271 store_path=os.getcwd() 272 user_path=os.path.join(store_path,'storage','user.json') 273 gift_path=os.path.join(store_path,'storage','gift.json') 274 base=Base(user_path,gift_path) 275 base.delete_gift(first_level='level1',second_level='level2',gift_name='iphone')
user.py
1 # coding:utf-8 2 3 from base import Base 4 from common.error import NotUserError,RoleError,UserActiveError,CountError 5 from common.utils import timestamp_to_string 6 import os 7 import random 8 ''' 9 1:user类的初始化 10 2:get_user(时间的转变) 11 3:查看奖品列表 12 4:抽奖函数 随机判断第一层(level1) 1:50% 2:30% 3:15% 4:5% 13 5:抽奖函数 随机判断第二层(level2) 1:80% 2:15% 3:5% 14 6:抽奖函数 获取到对应层级的真实奖品,并随即一个奖品,查看奖品count是否为0 15 不为零 中奖,提示用户,并奖品数量-1,并为用户更新 16 奖品到user表中的gifts中 17 数量为0,则未中奖 18 ''' 19 20 class User(Base): 21 def __init__(self,username,user_json,gift_json): 22 self.username=username 23 self.gift_random = list(range(1,101)) 24 super().__init__(user_json,gift_json) 25 self.get_user() 26 27 def get_user(self): 28 users=self._Base__read_users() 29 if self.username not in users: 30 raise NotUserError('not user %s'% self.username) 31 32 current_user=users.get(self.username) 33 if current_user.get('active') == False: 34 raise UserActiveError('the user %s had not use' % self.username) 35 36 if current_user.get('role') != 'normal': 37 raise RoleError('permission by normal') 38 39 self.user=current_user 40 self.name=current_user.get('username') 41 self.role=current_user.get('role') 42 self.gifts=current_user.get('gifts') 43 self.create_time=timestamp_to_string(current_user.get('create_time')) 44 45 def get_gifts(self): 46 gifts=self._Base__read_gifts() 47 gift_lists=[] 48 for level_one,level_one_pool in gifts.items(): 49 for level_two,level_two_pool in level_one_pool.items(): 50 for gift_name,gift_info in level_two_pool.items(): 51 gift_lists.append(gift_info.get('name')) 52 return gift_lists 53 54 def choice_gift(self): 55 #level1 get 56 first_level,second_level= None,None 57 self.get_user() 58 level_one_count=random.choice(self.gift_random) 59 if 1<=level_one_count<=50: 60 first_level = 'level1' 61 elif 51<=level_one_count<=80: 62 first_level = 'level2' 63 elif 81<=level_one_count<95: 64 first_level = 'level3' 65 elif level_one_count>=95: 66 first_level = 'level4' 67 else: 68 raise CountError("level_one_count need 0~100") 69 gifts = self._Base__read_gifts() 70 level_one=gifts.get(first_level) 71 72 level_two_count = random.choice(self.gift_random) 73 if 1<=level_two_count<=80: 74 second_level = 'level1' 75 elif 81<=level_two_count<95: 76 second_level = 'level2' 77 elif 95<=level_two_count<=100: 78 second_level = 'level3' 79 else: 80 raise CountError("level_one_count need 0~100") 81 level_two=level_one.get(second_level) 82 83 if len(level_two)<=0: 84 print('真可惜,您没有中奖') 85 return 86 87 gift_names=[] 88 for k,_ in level_two.items(): 89 gift_names.append(k) 90 gift_name=random.choice(gift_names) 91 gift_info = level_two.get(gift_name) 92 if gift_info.get('count') ==0: 93 print('真可惜,您没有中奖') 94 return 95 gift_info['count']-=1 96 level_two[gift_name]=gift_info 97 level_one[second_level]=level_two 98 gifts[first_level]=level_one 99 100 self._Base__save(gifts,self.gift_json) 101 self.user['gifts'].append(gift_name) 102 self.update() 103 print('恭喜您获得%s奖品'% gift_name) 104 105 106 def update(self): 107 users=self._Base__read_users() 108 users[self.username]=self.user 109 self._Base__save(users,self.user_json) 110 111 112 113 114 if __name__=='__main__': 115 store_path=os.getcwd() 116 user_path=os.path.join(store_path,'storage','user.json') 117 gift_path=os.path.join(store_path,'storage','gift.json') 118 user=User('王五',user_path,gift_path) 119 user.choice_gift()