python练习——moudule03——选课系统

# 作业需求
选课系统:
角色:学校、学员、课程、讲师
要求:
1. 创建北京、上海 2 所学校
2. 创建linux , python , go 3个课程 , linux\py 在北京开, go 在上海开
3. 课程包含,周期,价格,通过学校创建课程
4. 通过学校创建班级, 班级关联课程、讲师
5. 创建学员时,选择学校,关联班级
5. 创建讲师角色时要关联学校,
6. 提供两个角色接口
7.1 学员视图, 可以注册, 交学费, 选择班级,
7.2 讲师视图, 讲师可管理自己的班级, 上课时选择班级,
查看班级学员列表 , 修改所管理的学员的成绩
7.3 管理视图,创建讲师, 创建班级,创建课程
程序结构:

启动文件start.py

import os,sys
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(BASE_DIR)
sys.path.append(BASE_DIR)

from src.services import admin_service
from src.services import teacher_service
from src.services import student_service
from src.services import initialize_service
# BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(BASE_DIR)

def show_role():
    msg="""
    '0':初始化
    '1':管理员
    '2':老师
    '3':学生
    """
    print(msg)

def main():
    choice_dict={
        '0':initialize_service.main,
        '1':admin_service.main,
        '2':teacher_service.main,
        '3':student_service.main
    }
    show_role()
    while True:
        choice = input("请输入角色:").strip()
        if choice not in choice_dict:
            print("输入有误")
            continue
        else:
            choice_dict[choice]()
if __name__ == '__main__':
    main()
View Code

配置文件settings.py

import os

#选课系统变量
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(BASE_DIR)
ADMIN_DB = os.path.join(BASE_DIR,"db","admin")
SCHOOL_DB = os.path.join(BASE_DIR,"db","school")
TEACHER_DB = os.path.join(BASE_DIR,"db","teacher")
COURSE_DB = os.path.join(BASE_DIR,"db","course")
COURSE_TO_TEACHER_DB = os.path.join(BASE_DIR,"db","course_to_teacher")
CLASSES_DB = os.path.join(BASE_DIR,"db","classes")
STUDENT_DB = os.path.join(BASE_DIR,"db","student")
View Code

common.py中保存加密函数

import uuid,hashlib,time

def create_uuid():
    return str(uuid.uuid1())

def create_md5():
    m=hashlib.md5()
    m.update(bytes(str(time.time()),encoding="utf-8"))
    return m.hexdigest()

if __name__ == "__main__":
    print(create_uuid())
    print(create_md5())
View Code
initialize_service.py初始化admin
import getpass
from src.moudles import Admin

def initialize():
    try:
        user = input("输入初始化用户名:").strip()
        pwd = input("输入初始化密码:").strip()
        #pwd = getpass.getpass("输入初始化密码:").strip()
        obj = Admin(user,pwd)
        # print('123344')
        obj.save()
        # print('12')
        return True
    except Exception as e:
        print(str(e))

def main():
    show="""
    1.初始化管理员账户
    """
    choice_dict = {
        '1':initialize
    }
    while True:
        print(show)
        choice = input("请输入操作选项:").strip()

        if choice not in choice_dict:
            print('\033[43;1m选项错误,请重新输入!!!\033[0m')
        else:
            ret = choice_dict[choice]()
        if ret:
            print('操作成功')
            return
        else:
            print('操作异常,请重新操作')

if __name__ == '__main__':
    main()
View Code
admin_service.py
import os,sys
BASE_DIR=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# print(BASE_DIR)
sys.path.append(BASE_DIR)

from src.moudles import Admin
from src.moudles import School
from src.moudles import Teacher
from src.moudles import Course
from src.moudles import Classes
from src.moudles import Course_to_teacher
from src.moudles import Score
from src.moudles import Student

def create_school():
    try:
        name = input("输入学校名称:").strip()
        addr = input("输入学校地址:").strip()
        # print('33')
        school_list = [(obj.name, obj.addr) for obj in School.get_all_obj_list()]
        # school_list = [(obj.name, obj.addr) for obj in School.get_all_obj_list()]

        # print('44')
        # print(school_list)
        if (name,addr) in school_list:
            raise Exception('\033[33;1m[%s][%s]已经存在,不可重复创建\033[0m' %(name,addr))
        obj =School(name,addr)
        obj.save()
        status = True
        error = ''
        data='\033[33;1m[%s][%s]校区 创建成功\033[0m' %(obj.name,obj.addr)
    except Exception as e:
        status=False
        error = str(e)
        data = ''
    return {'status':status,'error':error,'data':data}


def show_school():
    for obj in School.get_all_obj_list():
        print('\033[35;1m学校[%s] 地址[%s] 创建日期[%s]\033[0m'.center(60,'-') \
              %(obj.name,obj.addr,obj.create_time))


def create_teacher():
    try:
        name = input("输入老师姓名:").strip()
        level = input("输入等级:").strip()
        teacher_list=[obj.name for obj in Teacher.get_all_obj_list()]
        if name in teacher_list:
            raise Exception('\033[33;1m[%s]已经存在,不可重复创建\033[0m' %(name))
        obj =Teacher(name,level)
        # print(obj.name,obj.addr)
        # print('bf save')
        obj.save()
        status=True

        # print('bf error')
        error = ''
        # print("bf data")
        data='\033[35;1m老师[%s]等级[%s] 创建成功\033[0m' %(obj.name,obj.level)
    except Exception as e:
        status=False
        error = str(e)
        data = ''
    return {'status':status,'error':error,'data':data}

def show_teacher():
    for obj in Teacher.get_all_obj_list():
        print('\033[35;1m老师[%s] 等级[%s] 创建日期[%s]\033[0m'.center(60,'-') \
              %(obj.name,obj.level,obj.create_time))


def create_course():
    try:
        print('创建课程'.center(60,'='))
        school_list = School.get_all_obj_list()
        for k,obj in enumerate(school_list):
            print(k,obj,obj.addr)
        sid = int(input('请输入学校:'))
        school_obj = school_list[sid]

        name = input("输入课程名称:").strip()
        price = input("输入课程价格:").strip()
        period = input("输入课程周期:").strip()

        course_list=[(obj.name,obj.nid.uuid) for obj in Course.get_all_obj_list()]#uuid???
        if (name,school_obj.nid.uuid) in course_list:
            raise Exception('\033[33;1m[%s]已经存在,不可重复创建\033[0m' %name)
        obj =Course(name,price,period,school_obj.nid)
        obj.save()
        status=True
        error = ''
        data='\033[33;1m课程[%s] 价格[%s] 周期[%s]创建成功\033[0m' %(obj.name,obj.price,obj.period)
    except Exception as e:
        status=False
        error = str(e)
        data = ''
    return {'status':status,'error':error,'data':data}

def show_course():
    for obj in Course.get_all_obj_list():
        print('\033[33;1m[%s] [%s]校区 [%s]课程 价格[%s] 周期[%s]\033[0m'.center(60, '-') \
              % (obj.school_nid.get_obj_by_uuid().name, obj.school_nid.get_obj_by_uuid().addr, \
                 obj.name, obj.price, obj.period))

def create_course_to_teacher():
    """
    self.course_nid = course_nid
    self.teacher_nid = teacher_nid
    :return:
    """
    try:
        #get teacher list
        teacher_list = Teacher.get_all_obj_list()
        for k,obj in enumerate(teacher_list):
            print(k,obj.name)
        tid = int(input('请输入老师:'))
        teacher_obj = teacher_list[tid]

        #get course list
        course_list = Course.get_all_obj_list()
        for k, obj in enumerate(course_list):
            print(k,obj.name)
        cid = int(input('请输入课程:'))
        course_obj = course_list[cid]
        print(course_obj.nid.get_obj_by_uuid().name)
        #course_list = [(obj.name, obj.school_nid.uuid) for obj in Course.get_all_obj_list()]  # uuid???
        course_to_teacher_list = [(obj.course_nid,obj.teacher_nid) for obj in Course_to_teacher.get_all_obj_list()]
        # print(course_to_teacher_list)
        for (course_obj.nid,teacher_obj.nid) in course_to_teacher_list:
            raise Exception('\033[33;1m[%s]  [%s]已经存在,不可重复创建\033[0m' % (obj.course_nid.get_obj_by_uuid().name, \
                                                                        obj.teacher_nid.get_obj_by_uuid().name))
        obj = Course_to_teacher(course_obj.nid,teacher_obj.nid)
        obj.save()
        status=True
        error = ''
        data = '\033[33;1m课程[%s] 老师[%s] 创建成功\033[0m' % (course_obj.name, teacher_obj.name)

    except Exception as e:
        status = False
        error = str(e)
        data = ''
    return {'status': status, 'error': error, 'data': data}

def show_course_to_teacher():
    # print('1')
    for obj in Course_to_teacher.get_all_obj_list():
        """
        self.nid = identifier.Course_to_teacherNid(self.db_path)
        self.course_nid = course_nid
        self.teacher_nid = teacher_nid"""
        # print(obj.nid,obj.course_nid,obj.teacher_nid)
        print(obj.course_nid.get_obj_by_uuid().name,obj.teacher_nid.get_obj_by_uuid().name)
        # print('\033[33;1m[%s] [%s]校区 [%s]班级 学费[%s] 课程老师对应表[%s]\033[0m'.center(60, '-') \
        #       % (obj.school_nid.get_obj_by_uuid().name, obj.school_nid.get_obj_by_uuid().addr, \
        #          obj.name, obj.tuition, obj.course_to_teacher_list))

def create_classes():
    """
    self.name = name
        self.tuition = tuition
        self.school_nid = school_nid
        self.course_to_teacher_list = course_to_teacher_list
    :return:
    """
    try:
        print('创建班级'.center(60,'='))
        #获取学校信息
        school_list = School.get_all_obj_list()
        for k,obj in enumerate(school_list):
            print(k,obj,obj.addr)
        sid = int(input('请输入学校:'))
        school_obj = school_list[sid]
        #显示课程,老师
        print("课程,老师列表".center(60,'-'))

        # course_to_teacher_list=[(obj.nid,obj.course_nid.get_obj_by_uuid().name,obj.teacher_nid.get_obj_by_uuid().name) for obj in Course_to_teacher.get_all_obj_list()]
        course_to_teacher_list=Course_to_teacher.get_all_obj_list()
        for k,obj in enumerate(course_to_teacher_list):
            print(k,obj.course_nid.get_obj_by_uuid().name,obj.teacher_nid.get_obj_by_uuid().name)
        c_t_tid=int(input('请输入课程:'))
        course_to_teacher_obj=course_to_teacher_list[c_t_tid]
        # show_course_to_teacher()


        # for obj in Course_to_teacher.get_all_obj_list():
        #     course_to_teacher_nid_list = [(obj.course_nid,obj.teacher_nid)]
        #     course_to_teacher_list = [(obj.course_nid.get_obj_by_uuid().name,obj.teacher_nid.get_obj_by_uuid().name)]
        #     print(course_to_teacher_list)
        # for i in course_to_teacher_list:
        #     print(i)
        #     print('\n')

        # course_list = Course.get_all_obj_list()
        # print("课程列表".center(60,'-'))
        # for k,obj in enumerate(course_list):
        #     print(k,obj.name)
        # cid = int(input('请输入课程:'))
        # course_obj = course_list[cid]
        #
        # teacher_list = Teacher.get_all_obj_list()
        # print("老师列表".center(60,'-'))
        # for k, obj in enumerate(teacher_list):
        #     print(k, obj.name)
        # tid = int(input('请输入老师:'))
        # teacher_obj = teacher_list[tid]
        # print(course_obj.nid,teacher_obj.nid)
        # for obj in course_to_teacher_list:
        #     print(obj)
        # ret = (course_obj.nid,teacher_obj.nid) in course_to_teacher_nid_list
        # course_to_teacher_nid=None
        # if ret:
        #     for obj in Course_to_teacher.get_all_obj_list():
        #         if obj.course_nid==course_obj.nid and obj.teacher_nid==teacher_obj.nid:
        #             course_to_teacher_nid=obj.nid
        # else:
        #     # print("输入的课程/老师有误")
        #     raise Exception('\033[33;1m输入的课程/老师有误\033[0m')
        name = input("输入班级名称:").strip()
        tuition = input("输入学费:").strip()
        classes_list=[obj.name for obj in Classes.get_all_obj_list()]#uuid???
        if name in classes_list:
            raise Exception('\033[33;1m班级[%s] 学费[%s]已经存在,不可重复创建\033[0m' %(name,tuition))
        obj =Classes(name,tuition,school_obj.nid,course_to_teacher_obj.nid)
        obj.save()
        status=True
        error = ''
        data='\033[33;1m班级[%s] 学费[%s]创建成功\033[0m' %(obj.name,obj.tuition)
    except Exception as e:
        status=False
        error = str(e)
        data = ''
    return {'status':status,'error':error,'data':data}

def show_classes():
    """
        self.name = name
        self.tuition = tuition
        self.school_nid = school_nid
        self.course_to_teacher_list = course_to_teacher_list
        :return:
        """
    for obj in Classes.get_all_obj_list():
        print('\033[33;1m[%s] [%s]校区 [%s]班级 学费[%s]\033[0m'.center(60, '-') \
              % (obj.school_nid.get_obj_by_uuid().name, obj.school_nid.get_obj_by_uuid().addr, \
                 obj.name, obj.tuition))

def create_student():
    try:
        name = input("输入学生姓名:").strip()
        age = input("输入学生年龄:").strip()
        sex = input("输入学生性别:").strip()
        qq = input("输入学生QQ:").strip()
        classes_list = Classes.get_all_obj_list()
        for k,obj in enumerate(classes_list):
            print(k,obj.name)
        cid = int(input("输入班级:").strip())
        classes_obj = classes_list[cid]
        score = None
        student_list=[(obj.name,obj.age,obj.sex,obj.classes_nid) for obj in Student.get_all_obj_list()]
        # student_list=Student.get_all_obj_list()

        # for obj in student_list:
        #     print(obj)
        if (name,age,sex,classes_obj.nid) in student_list:
            # print()
            raise Exception("\033[33;1m学生[%s] 年龄[%s]  性别[%s]   班级[%s]  已存在,不能重复创建" \
                            %(name,age,sex,classes_obj.name))
        # print('bf create student')
        obj = Student(name,age,sex,classes_obj.nid,score)
        # print('bf save')
        obj.save()
        # print('af save')
        status = True
        error =""
        data = "\033[35;1m学生[%s] 年龄[%s]  性别[%s]   班级[%s] 创建成功" %(obj.name,obj.age,obj.sex,classes_obj.name)
    except Exception as e:
        status = False
        error = str(e)
        data =""
    return {'status':status,'error':error,'data':data}

def show_student():
    for obj in Student.get_all_obj_list():
        print('\033[33;1m学生[%s] 年龄[%s] 性别[%s] 成绩[%s]\033[0m'.center(60, '-') \
              # % (obj.name,obj.age,obj.sex,obj.classes_nid.get_obj_by_uuid().name, obj.score))
              % (obj.name,obj.age,obj.sex, obj.score.score_dict))

def show():
    msg = '''
            0:选项
            1:创建学校
            2:查看学校
            3:创建老师
            4:查看老师
            5:创建课程
            6:查看课程
            7:创建班级
            8:查看班级
            9:关联老师与课程
            10:创建学生
            11:查看学生
            12:退出
        '''
    print(msg)

def main():
    login()
    choice_dic = {
        '0':show,
        '1':create_school,
        '2':show_school,
        '3':create_teacher,
        '4':show_teacher,
        '5':create_course,
        '6':show_course,
        '7':create_classes,
        '8':show_classes,
        '9':create_course_to_teacher,
        '10':create_student,
        '11':show_student,
        '12':exit
    }
    show()
    # print('1')
    while True:
        choice = input("请输入选项:").strip()
        if choice not in choice_dic:continue
        ret = choice_dic[choice]()
        if ret :
            if ret['status']:
                # print('11')
                print(ret['data'].center(60,'-'))
            else:
                # print("22")
                print(ret['error'].center(60,'-'))

def login():
    while True:
        ret = Admin.login()
        if ret:
            if ret['status']:
                print(ret['data'].center(60,'-'))
                break
            # main()
            else:
                print(ret['error'].center(60,'-'))
                # continue
# show_course_to_teacher()

if __name__ == '__main__':
    main()
    # show_school()
View Code
student_service.py
from src.services import admin_service
from src.moudles import Student

def register():
    """
    学生注册
    """
    # while True:
    print("学生注册".center(60,'-'))
    return admin_service.create_student()


"""
        try:
            name = input("输入学生姓名:").strip()
            age = input("输入学生年龄:").strip()
            sex = input("输入学生性别:").strip()
            qq = input("输入学生QQ:").strip()
            classes_list = Classes.get_all_obj_list()
            for k, obj in enumerate(classes_list):
                print(k, obj.name, obj)
            cid = int(input("输入班级:").strip())
            classes_obj = classes_list[cid]
            score = None
            student_list = [(obj.name, obj.age, obj.sex, obj.classes_nid) for obj in Student.get_all_obj_list()]
            for (name, age, sex, classes_obj.nid) in student_list:
                raise Exception(
                    "\033[43;1m学生[%s] 年龄[%s]  性别[%s]   班级[%s]  已存在,不能重复创建" % (name, age, sex, classes_obj.name))
            obj = Student(name, age, sex, classes_obj.nid, score)
            obj.save()
            status = True
            error = ""
            data = "\033[45;1m学生[%s] 年龄[%s]  性别[%s]   班级[%s] 创建成功" % (
            obj.name, obj.age, obj.sex, obj.classes_nid.get_obj_by_uuid().name)
        except Exception as e:
            status = False
            error = str(e)
            data = ""
        return {'status': status, 'error': error, 'data': data}
"""
def score():
    """
    学生查看个人成绩
    """
    name = input("请输入学生姓名:").strip()
    for obj in Student.get_all_obj_list():
        if obj.name== name:
            # print('ert')
            ret ='\033[33;1m学生[%s] 成绩[%s]\033[0m' \
              % (obj.name, obj.score.score_dict)
            print(ret)
            return ret
    raise Exception('\033[35;1m查成绩出错\033[0m')



def main():
    msg ="""
    '1':'注册'
    '2':'查看分数'
    """
    choice_dict={
        '1':register,
        '2':score
    }
    while True:
        print(msg)
        choice = input("请输入选项:").strip()
        if choice not in choice_dict:
            print("\033[33;1m输入有误\033[1m")
            continue
        else:
            ret = choice_dict[choice]()
        if ret:
            print('操作成功')
            return
        else:
            print('操作异常,请重新操作')
if __name__ == '__main__':
    main()
View Code
identifier.py
from lib import commons
import pickle,os

class Nid:
    def __init__(self,role,db_path):
        role_list = [
            'admin','teacher','school',"course",'course_to_teacher','classes','student'
        ]
        # print('1')
        if role not in role_list:
            raise Exception('角色定义有误,选项为:%s' %(",".join(role_list)))
        # print('2')
        self.uuid =commons.create_uuid()
        # print('3')
        self.db_path = db_path
        # print('4')
        self.role = role
        # print('5')

    def __str__(self):
        return self.uuid

    def get_obj_by_uuid(self):

        for filename in os.listdir(self.db_path):
            if filename == self.uuid:
                file_path = os.path.join(self.db_path, self.uuid)
                return pickle.load(open(file_path,'rb'))
        return None


class AdminNid(Nid):
    def __init__(self,db_path):
        super(AdminNid,self).__init__('admin',db_path)
        # print('121')
class SchoolNid(Nid):
    def __init__(self,db_path):
        super(SchoolNid,self).__init__('school',db_path)
    # pass

class TeacherNid(Nid):
    def __init__(self,db_path):
        super(TeacherNid,self).__init__('teacher',db_path)
    # pass

class CourseNid(Nid):
    def __init__(self,db_path):
        super(CourseNid,self).__init__('course',db_path)
    # pass

class Course_to_teacherNid(Nid):
    def __init__(self,db_path):
        super(Course_to_teacherNid,self).__init__('course_to_teacher',db_path)
    # pass

class ClassesNid(Nid):
    def __init__(self,db_path):
        super(ClassesNid,self).__init__('classes',db_path)
    # pass

class StudentNid(Nid):
    def __init__(self,db_path):
        super(StudentNid,self).__init__('student',db_path)
View Code

moudles.py

# Date: 2017/10/23
import os,sys
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(BASE_DIR)
sys.path.append(BASE_DIR)
from src import identifier
import pickle,os,time
from conf import settings
class BaseModel:
    def save(self):
        file_path= os.path.join(self.db_path,str(self.nid))
        f = open(file_path,"wb")
        pickle.dump(self,f)
        f.close()

    @classmethod
    def get_all_obj_list(cls):
        # print('in the get_all_obj_list()')
        ret = []
        for filename in os.listdir(cls.db_path):
            if filename:
                file_path = os.path.join(cls.db_path, filename)
                f = open(file_path, 'rb')
                ret.append(pickle.load(f))
                f.close()
        return ret

class Admin(BaseModel):
    db_path = settings.ADMIN_DB
    def __init__(self,username,password):
        self.nid = identifier.AdminNid(self.db_path)
        self.username = username
        self.password = password
        self.create_time = time.strftime('%Y-%m-%d')

    @staticmethod
    def login():
        try:
            name = input("请输入用户名:").strip()
            pas = input("请输入密码:").strip()
            for obj in Admin.get_all_obj_list():
                if obj.username == name and obj.password == pas:
                    status =True
                    error =''
                    data = '\033[35;1m登陆成功\033[0m'
                    break
            else:
                raise Exception("\033[33;1m用户名或密码错误\033[0m")
        except Exception as e:
            status =False
            error = str(e)
            data =''
        return {'status':status,'error':error,'data':data}

class School(BaseModel):
    db_path = settings.SCHOOL_DB
    def __init__(self,name,addr):
        self.nid = identifier.SchoolNid(self.db_path)
        self.name = name
        self.addr = addr
        self.__income = 0
        self.create_time = time.strftime('%Y-%m-%d %X')

    def __str__(self):
        return self.name

class Teacher(BaseModel):
    db_path = settings.TEACHER_DB
    def __init__(self,name,level):
        # print('db')
        self.nid = identifier.TeacherNid(self.db_path)
        # print('name')
        self.name = name
        # print('level')
        self.level = level
        # print('account')
        self.__account = 0
        # print('time')
        self.create_time = time.strftime('%Y-%m-%d %X')

class Course(BaseModel):
    db_path = settings.COURSE_DB
    def __init__(self,name,price,period,school_nid):
        self.nid = identifier.CourseNid(self.db_path)
        self.name = name
        self.price = price
        self.period = period
        self.school_nid = school_nid

class Course_to_teacher(BaseModel):
    db_path = settings.COURSE_TO_TEACHER_DB
    def __init__(self,course_nid,teacher_nid):
        self.nid = identifier.Course_to_teacherNid(self.db_path)
        self.course_nid = course_nid
        self.teacher_nid = teacher_nid

    def get_course_to_teacher_list(self):
        ret = self.get_all_obj_list()
        # if ret:

        res = [(obj.course_nid.get_obj_by_uuid(),obj.teacher_nid.get_obj_by_uuid()) \
               for obj in ret]
        return res

class Classes(BaseModel):
    db_path = settings.CLASSES_DB
    def __init__(self,name,tuition,school_nid,course_to_teacher_list):
        self.nid = identifier.ClassesNid(self.db_path)
        self.name = name
        self.tuition = tuition
        self.school_nid = school_nid
        self.course_to_teacher_list = course_to_teacher_list

class Score:
    def __init__(self,nid):
        self.nid=nid  #nid指学生的id
        self.score_dict={}

    def set(self,course_to_teacher_nid,number):
        self.score_dict[course_to_teacher_nid]=number

    def get(self,course_to_teacher_nid):
        return self.score_dict.get(course_to_teacher_nid)

class Student(BaseModel):
    db_path = settings.STUDENT_DB
    def __init__(self,name,age,sex,qq,classes_nid):
        self.nid = identifier.ClassesNid(self.db_path)
        self.name = name
        self.age = age
        self.sex = sex
        self.qq = qq
        self.classes_nid = classes_nid
        self.score = Score(self.nid)


    # pass
View Code

 

posted @ 2017-10-25 18:33  云上有龙  阅读(324)  评论(0编辑  收藏  举报