老师,我代码有点奇怪,小慕的role 在user.py里面显示的是admin,在base里查询小慕的role是normal

老师,我代码有点奇怪,小慕的role 在user.py里面显示的是admin,在base里查询小慕的role是normal

在user.by里面查询 小慕的role是admin,但是我前面有做判断如果是admin就抛出错误,但是没有抛出错误

https://img1.sycdn.imooc.com//climg/62bec95f084ea95819201048.jpghttps://img1.sycdn.imooc.com//climg/62bec96808168df519201048.jpghttps://img1.sycdn.imooc.com//climg/62bec9ab08e4841119201048.jpg

user.by

# coding-utf-8

import os

from common.error import NotUserError, UserActiveError, RoleError
from common.utils import timestamp_to_string
from base import Base


class User(Base):
    def __init__(self, username, user_json, gift_json):
        self.username = username
        super().__init__(user_json, gift_json)

    def get_user(self):
        users = self._Base__read_users()
        if self.username not in users:
            raise NotUserError('not user %s' % self.username)
        current_user = users.get(self.username)
        if current_user['active'] == False:
            raise UserActiveError('the user %s had not use' % self.username)
        if current_user.get('role') != 'normal':
            RoleError('permission by normal')
        self.name = current_user['username']
        self.role = current_user.get('role')
        self.gifts = current_user.get('gifts')
        self.create_time = timestamp_to_string(current_user.get('create_time'))


if __name__ == '__main__':
    gift_path = os.path.join(os.getcwd(), 'storage', 'gift.json')
    user_path = os.path.join(os.getcwd(), 'storage', 'user.json')
    user = User('小慕', gift_json=gift_path, user_json=user_path)
    user.get_user()
    print(user.user, user.name, user.gifts, user.role, user.create_time)





base.by

# coding-utf-8


import os
import json
import time
from common.consts import ROLES, FIRSTLEVELS, SECONDLEVELS
from common.error import UserExistsError, RoleError, LevelError, NegativeNumber, CountError
from common.utils import check_file, timestamp_to_string


class Base:
    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_gift()

    def check_user_json(self):
        check_file(self.user_json)

    def check_gift_json(self):
        check_file(self.gift_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:
            for k, v in data.items():
                v['create_time'] = timestamp_to_string(v['create_time'])
                v['update_time'] = timestamp_to_string(v['update_time'])
                data[k] = v
        return data

    def __write_users(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'] = time.time()
        user['create_time'] = time.time()
        user['gifts'] = []
        users = self.__read_users()
        if user['username'] in users:
            raise UserExistsError('username %s had exists' % user['username'])
        users.update(
            {user['username']: user}
        )
        self.user_json(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 ROLES:
            raise RoleError('not user role %s' % role)
        user['role'] = role
        user['update_time'] = 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'] = time.time()
        users[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
        users.pop(username)
        self.__save(users, self.user_json)

    def __read_gift(self):
        check_file(self.gift_json)
        with open(self.gift_json, 'r') as f:
            data = json.loads(f.read())
        return data

    def __init_gift(self):
        data = {
            'level1': {
                'level1': {},
                'level2': {},
                'level3': {}
                    },
            'level2': {
                'level1': {},
                'level2': {},
                'level3': {}
            },
            'level3': {
                'level1': {},
                'level2': {},
                'level3': {}
            },
            'level4': {
                'level1': {},
                'level2': {},
                'level3': {}
            }
        }
        gifts = self.__read_gift()
        if len(gifts) != 0:
            return
        self.__save(data, self.gift_json)

    def __write_gifts(self, first_level, second_level, gift_name, gift_count):
        if first_level not in FIRSTLEVELS:
            raise LevelError('first_level not exists')
        if second_level not in SECONDLEVELS:
            raise LevelError('second_level not exists')
        gifts = self.__read_gift()
        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)
        print(gifts)

    def __update(self, first_level, second_level, gift_name, gift_count=1, is_admin=False):
        assert isinstance(gift_count, int), 'gift count is int'
        data = self.check_and_get_gift(first_level, second_level, gift_name)
        current_second_gift_pool = data.get('level_two')
        current_gift_pool = data.get('level_one')
        gifts = data.get('gifts')
        current_gifts = current_second_gift_pool[gift_name]
        if gift_count <= 0:
            raise CountError('gift count not 0')
        if is_admin == True:
            current_gifts['count'] = gift_count
        else:
            if current_gifts['count'] - gift_count <= 0:
                raise NegativeNumber('gift count can not negative')
            current_gifts['count'] -= gift_count
        current_second_gift_pool[gift_name] = current_gifts
        current_gift_pool[second_level] = current_second_gift_pool
        gifts[first_level] = current_gift_pool
        self.__save(gifts, self.gift_json)

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

    def check_and_get_gift(self, first_level, second_level, gift_name):
        if first_level not in FIRSTLEVELS:
            raise LevelError('first_level not exists')
        if second_level not in SECONDLEVELS:
            raise LevelError('second_level not exists')
        gifts = self.__read_gift()
        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_get_gift(first_level, second_level, gift_name)
        if not data:
            return data
        current_gift_pool = data.get('level_one')
        current_second_gift_pool = data.get('level_two')
        gifts = data.get('gifts')
        delete_gift = current_gift_pool[second_level].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


if __name__ == '__main__':
    gift_path = os.path.join(os.getcwd(), 'storage', 'gift.json')
    user_path = os.path.join(os.getcwd(), 'storage', 'user.json')
    base = Base(user_json=user_path, gift_json=gift_path)
    # base.write_users(username='dewei', role='admin')

    # base._Base__change_active('小慕')
    result = base._Base__read_users()
    # base.update(first_level='level1', second_level='level2', gift_name='iphone12', gift_count=1)
    print(result)


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

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

1回答
好帮手慕小猿 2022-07-01 19:04:20

同学,你好!老师这边运行同学的代码是没有问题的,两个文件运行的role 结果是一致的,同学可以将完整的项目代码发送至1757578369@qq.com邮箱,老师这边运行代码看下具体问题。祝学习愉快!

  • 提问者 慕尼黑1183503 #1

    老师,代码已发送过去了,麻烦帮忙看下哈~

    2022-07-01 19:49:02
  • 好帮手慕小猿 回复 提问者 慕尼黑1183503 #2

    同学,你好!1、同学出现角色不同是因为同学user.json 文件中存在两条小慕的记录,其中最后一条是错误的数据,应该用“小慕”做为键来取“小慕”的所有信息,并不应该存在键为“username”的数据,删除键为“username”的数据即可
    https://img1.sycdn.imooc.com//climg/62bfbb6a09873baf04830558.jpg
    2、保存用户信息要用self.__save()方法,self.user_json 是实例化属性,不能当方法使用
    https://img1.sycdn.imooc.com//climg/62bfbbd409bfb18705200204.jpg


    3、没有抛出异常是因为没有使用raise手动抛出异常
    https://img1.sycdn.imooc.com//climg/62bfbbf5097c5cf305490114.jpg
    祝学习愉快~

    2022-07-02 11:31:24
问题已解决,确定采纳
还有疑问,暂不采纳

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

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

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

在线咨询

领取优惠

免费试听

领取大纲

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