提示我ValueError: Circular reference detected

提示我ValueError: Circular reference detected

class Base(object):
   def __init__(self, user_json, gift_json):
       self.user_json = user_json
       self.gift_json = gift_json

       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.json
   def __read_users(self, time_to_str=False):
       with open(self.user_json, 'r') as f:
           data = json.loads(f.read())

       if time_to_str == True:
           for username, v in data.items():
               v['create_time'] = timestamp_to_string(v['create_time'])
               v['update_time'] = timestamp_to_string(v['update_time'])
               data[username] = v
       return data

   def __write_user(self, **user):
       if 'username' not in user:
           raise ValueError('missing username')
       if 'role' not in user:
           raise ValueError('missing role')
       user['active'] = True
       user['create_time'] = timestamp_to_string(time.time())
       user['update_time'] = timestamp_to_string(time.time())
       user['gift'] = []

       users = self.__read_users()

       if user['username'] in users:
           raise error.UserExistsError('username %s had exists' % user['username'])

       users.update(
           {user['username']: user}
       )
       self.__save(users, self.user_json)

   # 用户修改与删除
   def __change_role(self, username, role):
       users = self.__read_users()
       user = users.get(username)

       if not user:
           return False
       if role not in consts.ROLES:
           raise error.RoleError('not use role %s' % role)

       user['role'] = role
       user['update_time'] = timestamp_to_string(time.time())
       users[username] = user
       self.__save(users, self.user_json)
       return True

   def __change_active(self, username):
       users = self.__read_users()
       user = users.get(username)
       if not user:
           return False

       user['active'] = not user['active']
       user['update_time'] = timestamp_to_string(time.time())
       user[username] = user
       self.__save(users, self.user_json)
       return True

   def __delete_user(self, username):
       users = self.__read_users()
       user = users.get(username)

       if not user:
           return False

       delete_user = users.pop(username)
       self.__save(users, self.user_json)
       return delete_user

   # 奖品初始化写入与读取
   def __read_gifts(self):
       with open(self.gift_json) as f:
           data = json.loads(f.read())
       return data

   def __init_gifts(self):
       data = {
           'level1': {
               'level1': {},
               'level2': {},
               'level3': {}
           },
           'level2': {
               'level1': {},
               'level2': {},
               'level3': {}
           },
           'level3': {
               'level1': {},
               'level2': {},
               'level3': {}
           },
           'level4': {
               'level1': {},
               'level2': {},
               'level3': {}
           }
       }
       gifts = self.__read_gifts()
       if len(gifts) != 0:
           return

       self.__save(data, self.gift_json)

   def __write_gift(self, first_level, second_level, gift_name, gift_count):
       if first_level not in consts.FIRSTLEVELS:
           raise error.LevelError('firstlevel no exists')
       if second_level not in consts.SECONDLEVELS:
           raise error.LevelError('secondlevel no exists')

       gifts = self.__read_gifts()

       current_gift_pool = gifts[first_level]
       current_second_gift_pool = current_gift_pool[second_level]

       if gift_count <= 0:
           gift_count = 1

       if gift_name in current_second_gift_pool:
           current_second_gift_pool[gift_name]['count'] = current_second_gift_pool[gift_name]['count'] + gift_count
       else:
           current_second_gift_pool[gift_name] = {
               'name': gift_name,
               'count': gift_count
           }

       current_gift_pool[second_level] = current_second_gift_pool
       gifts[first_level] = current_gift_pool
       self.__save(gifts, self.gift_json)

   # 奖品数量的减少和删除
   def __gift_update(self, first_level, second_level, gift_name, gift_count=1):
       data = self.__check_and_getgift(first_level, second_level, gift_name)

       if data == False:
           return False

       current_gift_pool = data.get('level_one')
       current_second_gift_pool = data.get('level_two')
       gifts = data.get('gifts')

       current_gift = current_second_gift_pool[gift_name]

       if current_gift['count'] - gift_count < 0:
           raise error.NegativeNumberError('gift count can not nagetive')

       current_gift['count'] -= gift_count
       current_second_gift_pool[gift_name] = current_gift
       current_gift_pool[second_level] = current_second_gift_pool
       gifts[first_level] = current_gift_pool

       self.__save(gifts, self.gift_json)

   def __check_and_getgift(self, first_level, second_level, gift_name):
       if first_level not in consts.FIRSTLEVELS:
           raise error.LevelError('firstlevel no exists')
       if second_level not in consts.SECONDLEVELS:
           raise error.LevelError('secondlevel no exists')

       gifts = self.__read_gifts()

       level_one = gifts[first_level]
       level_two = level_one[second_level]

       if gift_name not in level_two:
           return False

       return {
           'level_one': level_one,
           'level_two': level_two,
           'gifts': gifts
       }

   def delete_gift(self, first_level, second_level, gift_name):
       data = self.__check_and_getgift(first_level, second_level, gift_name)

       if data == False:
           return False

       current_gift_pool = data.get('level_one')
       current_second_gift_pool = data.get('level_two')
       gifts = data.get('gifts')

       delete_gift_dara = current_second_gift_pool.pop(gift_name)
       current_gift_pool[second_level] = current_second_gift_pool
       gifts[first_level] = current_gift_pool
       self.__save(gifts, self.gift_json)
       return delete_gift_dara

   # 保存
   def __save(self, data, path):
       json_data = json.dumps(data)
       with open(path, 'w') as f:
           f.write(json_data)

----------------------------------------------

class Admin(Base):
   # admin类的搭建
   def __init__(self, username, user_json, gift_json):
       self.username = username
       super().__init__(user_json=user_json, gift_json=gift_json)
       self.get_user()

   # 获取用户函数(包含获取身份)
   def get_user(self):
       users = self._Base__read_users()
       current_user = users.get(self.username)

       if current_user == None:
           raise error.NotUserError(f'not user {self.username}')
       if current_user.get('active') == False:
           raise error.UserActiveError(f'the user {self.username} had not use')

       self.user = current_user
       self.role = current_user.get('role')
       self.name = current_user.get('username')
       self.active = current_user.get('active')
       # print(users)

   # 添加用户(判断当前身份是否是管理员)
   def add_user(self, username, role):
       if self.role != 'admin':
           raise Exception('permission')
       self._Base__write_user(username=username, role=role)

   # 冻结与恢复用户
   def update_user_active(self, username):
       if self.role != 'admin':
           raise Exception('permission')
       self._Base__change_active(username=username)


if __name__ == '__main__':
   gift_path = os.path.join(os.getcwd(), 'storage', 'gift.json')
   user_path = os.path.join(os.getcwd(), 'storage', 'user.json')
   admin = Admin('dewei', user_json=user_path, gift_json=gift_path)
   admin.update_user_active(username='小慕')

------------------------------------------------------

Traceback (most recent call last):

  File "E:/慕课网/gift/admin.py", line 57, in <module>

    admin.update_user_active(username='小慕')

  File "E:/慕课网/gift/admin.py", line 50, in update_user_active

    self._Base__change_active(username=username)

  File "E:\慕课网\gift\base.py", line 173, in __change_active

    self.__save(users, self.user_json)

  File "E:\慕课网\gift\base.py", line 309, in __save

    json_data = json.dumps(the_data)


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

2回答
好帮手慕美 2020-08-24 09:55:56

同学,你好。同学应修改下图中的位置,在base.py文件中的__change_active()中,应该是users

http://img1.sycdn.imooc.com//climg/5f431e04094bf12008100323.jpg

如果我的回答解决了您的疑惑,请采纳!祝学习愉快~~~~

好帮手慕乃馨 2020-08-22 18:33:38

同学你好,标题中有ValueError: Circular reference detected,但是提供的代码中错误没有这个提示,是不是错误没有粘贴全?麻烦截图完整的错误提示,我们为你做具体解答~

  • C:\Users\Administrator\venv\Scripts\python.exe E:/慕课网/gift/admin.py Traceback (most recent call last): File "E:/慕课网/gift/admin.py", line 57, in <module> admin.update_user_active(username='小慕') File "E:/慕课网/gift/admin.py", line 50, in update_user_active self._Base__change_active(username=username) File "E:\慕课网\gift\base.py", line 173, in __change_active self.__save(users, self.user_json) File "E:\慕课网\gift\base.py", line 309, in __save json_data = json.dumps(data) File "E:\Anaconda\Anaconda3\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "E:\Anaconda\Anaconda3\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "E:\Anaconda\Anaconda3\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) ValueError: Circular reference detected Process finished with exit code 1
    2020-08-22 18:36:20
  • 同学你好,可以修改代码 admin.update_user_active(username=u"小慕") 尝试解决。祝学习愉快~
    2020-08-22 19:08:35
  • 不行啊 还是会报错 C:\Users\Administrator\venv\Scripts\python.exe E:/慕课网/gift/admin.py Traceback (most recent call last): File "E:/慕课网/gift/admin.py", line 58, in <module> admin.update_user_active(username=u"小慕") File "E:/慕课网/gift/admin.py", line 50, in update_user_active self._Base__change_active(username=username) File "E:\慕课网\gift\base.py", line 173, in __change_active self.__save(users, self.user_json) File "E:\慕课网\gift\base.py", line 309, in __save json_data = json.dumps(data) File "E:\Anaconda\Anaconda3\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "E:\Anaconda\Anaconda3\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "E:\Anaconda\Anaconda3\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) ValueError: Circular reference detected Process finished with exit code 1
    2020-08-23 01:04:15
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师