关于课后作业添加进程锁
# coding:utf-8 import json import os import time from common.utils import check_file, timestamp_to_str, save from common.error import UserExistsError, RoleError, LevelError, CountError from common.consts import ROLES, FIRST_LEVELS, SECOND_LEVELS from multiprocessing import Lock class Base(object): def __init__(self, user_json, gift_json): self.user_json = user_json self.gift_json = gift_json self.lock = Lock() self.__check_user_json() self.__check_gift_json() self.__init_gifts() # 文件检查 def __check_user_json(self): check_file(self.user_json) def __check_gift_json(self): check_file(self.gift_json) # 操作user: # 读取users def __read_users(self, time_to_str=False): self.lock.acquire() try: with open(self.user_json, 'r', encoding='utf-8') as f: json_data = json.loads(f.read()) if time_to_str: for k, v in json_data.items(): v['create_time'] = timestamp_to_str(v['create_time']) v['update_time'] = timestamp_to_str(v['update_time']) json_data[k] = v except Exception as e: raise e finally: self.lock.release() return json_data # 增加user def __write_user(self, **user): if 'username' not in user: raise ValueError('缺少username') if 'role' not in user: raise ValueError('缺少role') user['active'] = True user['create_time'] = time.time() user['update_time'] = time.time() user['gifts'] = [] self.lock.acquire() try: users = self.__read_users() if user['username'] in users: raise UserExistsError('用户 %s 已存在' % user['username']) users.update( {user['username']: user} ) save(self.user_json, users) except Exception as e: raise e finally: self.lock.release() # 修改role def __change_role(self, username, role): self.lock.acquire() try: users = self.__read_users() user = users.get(username) if not user: return False if role not in ROLES: raise RoleError('role只能是admin或者normal') user['role'] = role user['update_time'] = time.time() users[username] = user save(self.user_json, users) except Exception as e: raise e finally: self.lock.release() return True # 修改active def __change_active(self, username): self.lock.acquire() try: users = self.__read_users() user = users.get(username) if not user: return False user['active'] = not user['active'] user['update_time'] = time.time() users[username] = user save(self.user_json, users) except Exception as e: raise e finally: self.lock.release() return True # 删除user def __delete_user(self, username): self.lock.acquire() try: users = self.__read_users() user = users.get(username) if not user: return False del_user = users.pop(username) save(self.user_json, users) except Exception as e: raise e finally: self.lock.release() return del_user # 操作gift # 读取gifts def __read_gifts(self): self.lock.acquire() try: with open(self.gift_json, 'r', encoding='utf-8') as f: json_gifts = json.loads(f.read()) except Exception as e: raise e finally: self.lock.release() return json_gifts # gift结构初始化 def __init_gifts(self): data = { 'level1': { 'level1': {}, 'level2': {}, 'level3': {} }, 'level2': { 'level1': {}, 'level2': {}, 'level3': {} }, 'level3': { 'level1': {}, 'level2': {}, 'level3': {} }, 'level4': { 'level1': {}, 'level2': {}, 'level3': {} } } self.lock.acquire() try: gifts = self.__read_gifts() if len(gifts) != 0: return save(self.gift_json, data) except Exception as e: raise e finally: self.lock.release() # 判断gift等级合理性及获取gifts def __check_get_gifts(self, first_level, second_level): if first_level not in FIRST_LEVELS: raise LevelError('第一层level等级错误,只能是level1~level4') if second_level not in SECOND_LEVELS: raise LevelError('第二层level等级错误,只能是level1~level3') self.lock.acquire() try: gifts = self.__read_gifts() except Exception as e: raise e finally: self.lock.release() level_one = gifts[first_level] level_two = level_one[second_level] return { 'level_one': level_one, 'level_two': level_two, 'gifts': gifts } # 添加gift def __write_gift(self, first_level, second_level, gift_name, gift_count): assert isinstance(gift_count, int), '礼物数量必须是int' data = self.__check_get_gifts(first_level, second_level) gifts = data.get('gifts') level_one = data.get('level_one') level_two = data.get('level_two') if gift_count <= 0: gift_count = 1 if gift_name in level_two: level_two[gift_name]['count'] = level_two[gift_name]['count'] + gift_count else: level_two[gift_name] = { 'name': gift_name, 'count': gift_count } level_one[second_level] = level_two gifts[first_level] = level_one self.lock.acquire() try: save(self.gift_json, gifts) except Exception as e: raise e finally: self.lock.release() # gift数量修改(根据gift_count数量递减) def __update_gift(self, first_level, second_level, gift_name, gift_count=1, is_admin=False): assert isinstance(gift_count, int), '礼物数量必须是int' data = self.__check_get_gifts(first_level, second_level) gifts = data.get('gifts') level_one = data.get('level_one') level_two = data.get('level_two') if gift_name not in level_two: return False if is_admin: if gift_count <= 0: raise CountError('礼物数量错误') level_two[gift_name]['count'] = gift_count else: if level_two[gift_name]['count'] - gift_count < 0: raise CountError('礼物数量错误') level_two[gift_name]['count'] -= gift_count level_one[second_level] = level_two gifts[first_level] = level_one self.lock.acquire() try: save(self.gift_json, gifts) except Exception as e: raise e finally: self.lock.release() return True # gift的删除 def __delete_gift(self, first_level, second_level, gift_name): data = self.__check_get_gifts(first_level, second_level) gifts = data.get('gifts') level_one = data.get('level_one') level_two = data.get('level_two') if gift_name not in level_two: return False del_gift = level_two.pop(gift_name) level_one[second_level] = level_two gifts[first_level] = level_one self.lock.acquire() try: save(self.gift_json, gifts) except Exception as e: raise e finally: self.lock.release() return del_gift
请老师看一下这样添加进程锁对不对,还有请问对于读取json文件时有必要添加进程锁吗以及加锁时有必要加except代码块吗?还是只用try...finally就可以
15
收起
正在回答 回答被采纳积分+1
1回答
Python全能工程师
- 参与学习 人
- 提交作业 16233 份
- 解答问题 4470 个
全新版本覆盖5大热门就业方向:Web全栈、爬虫、数据分析、软件测试、人工智能,零基础进击Python全能型工程师,从大厂挑人到我挑大厂,诱人薪资在前方!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星