上一篇:生成器 | 手把手教你入门Python之八十一
下一篇:模块的使用| 手把手教你入门Python之八十三
本文来自于千锋教育在阿里云开发者社区学习中心上线课程《Python入门2020最新大课》,主讲人姜伟。
学生管理系统
一个学生信息对应一个字典
整个系统的所有学生:所有学生对应一个列表,列表中的元素全是字典
整个系统:一个字典,字典中有一个key(all_student)
对应的值是所有学生;
这个字典需要做数据持久化,将数据存储到json文件中,文件名就是当前登录的账号名
jack.json
{
'all_student': [
{'name':'张三', 'age':89, 'tel':'237837293'},
{'name':'张三', 'age':89, 'tel':'237837293'},
{'name':'张三', 'age':89, 'tel':'237837293'},
{'name':'张三', 'age':89, 'tel':'237837293'}
],
'num':4
}
新建文件:welcome.txt
===================================
** 欢迎xx来到学生管理系统 **
♦ 1. 登 录
♦ 2. 注 册
♦ 3. 退 出
===================================
新建文件:students_page.txt
===================================
🌺🌺欢迎%s:
♥ 1. 添加学生
♥ 2. 查看学生
♥ 3. 修改学生信息
♥ 4. 删除学生
♥ 5. 返回
===================================
index.py:
import sys
import file_manager
import model
import student_manager
def register():
# 读取文件,查看文件里是否有数据,如果文件不存在,默认是一个字典
data = file_manager.read_json('data.json', {})
while True:
teacher_name = input('请输入账号(3~6位):')
if not 3 <= len(teacher_name) <= 6:
print('账号不符合要求,请重新输入!')
else:
break
if teacher_name in data:
print('注册失败!该账号已经注册过!')
return
while True:
password = input('请输入密码(6~12):')
if not 6 <= len(password) <= 12:
print('密码不符合要求,请重新输入!')
else:
break
# 用户名密码都已经输入正确以后,创建一个teacher对象{'zhang':'123456'}
t = model.Teacher(teacher_name, password)
data[t.name] = t.password
# data[teacher_name] = password
file_manager.write_json('teacher.json', teacher)
def login():
# 读取文件,查看文件里是否有数据,如果文件不存在,默认是一个字典
data = file_manager.read_json('data.json', {})
teacher_name = input('请输入老师账号:')
if teacher_name not in data:
print('登录失败!该账号没有注册!')
return
password = input('请输入密码:')
import tools
if data[teacher_name] == tools.encrypt_password(password):
student_manager.name = teacher_name
student_manager.show_manager()
else:
print('密码错误,登录失败!')
def start():
content = file_manager.read_file('welcome.txt')
while True:
operator = input(content + '\n请选择(1-3):')
if operator == '1':
login()
elif operator == '2':
register()
elif operator =='3':
# break # 停止死循环
# exit(0) # 退出整个程序
sys.exit(0)
else:
print('输入有误!')
if __name__ = '__main__':
start()
file_manager.py:
base_dir = './files/'
def read_file(file_name)
try:
with open('base_dir' + file_name, 'r', encoding='utf8') as file:
content= file.read()
return content
except FileNotFoundError:
print('文件未找到')
def write_json(file_name, data):
with open(base_dir + file_name, 'w', encoding='utf8') as file:
import json
json.dump(data, file)
def read_json(file_name, default_data):
try:
with open('base_dir' + file_name, 'r', encoding='utf8') as file:
import json
return json.load(file)
except FileNotFoundError:
# print('文件未找到')
return default_data
student_manager.py:
import model
name = ''
def add_student():
x = file_manager.read_json(name + '.json', {})
if not x:
students = []
num = 0
else:
students = x['all_student']
num = int(x['num'])
while True:
s_name = input('请输入学生姓名:')
s_age = input('请输入年龄:')
s_gender = input('请输入性别:')
s_tel = input('请输入电话号码:')
num += 1
# 字符串的zfill方法,在字符串的前面补0
s_id = 'stu_' + str(num).zfill(4)
# 创建一个Student对象
s = model.Student(s_id, s_name, s_age, s_gender, s_tel)
# {
# 'all_student': [
# {'name':'zhangsan', 'age':18, 'gender':'男', 'tel':'110'},
# {'name':'zhangsan', 'age':18, 'gender':'男', 'tel':'110'}
# ],
# 'num':2
# }
students.append(s.__dict__)
# 拼接字典
data = {'all_student': students, 'num':len(students)}
# print(data)
# 把数据写进文件里
file_manager.write_json(name + '.json', data)
choice = input('添加成功!\n1.继续\n2.返回\n请选择(1-2):')
if choice =='2':
break
def show_student():
key = value = ''
x = input('1.查看所有学生\n2.根据姓名查找\n3.根据学号查找\n其他:返回\n请选择:')
y = file_manager.read_json(name + '.json', {})
students = y.get('all_student', [])
if not students:
print('该老师还没有学员,请添加学员')
return
if x == '1': # 查询所有
pass
elif x == '2':
value = input('请输入学员的姓名:')
key = 'name'
elif x == '3':
value = input('请输入学员的id:')
key = 's_id'
else:
return
students = filter(lambda s: s.get(key, '') == value, students)
if not students:
print('未找到学员')
return
for Student in students:
print('学号: {s_id}, 姓名: {name}, 性别: {gender}, 年龄: {age}, ☎: {tel}'.format(**student))
def modify_student():
pass
def delte_student():
y = file_manager.read_json(name + '.json', {})
students = y.get('all_student', [])
key = value = ''
if not students:
print('该老师还没有学员,请添加学员')
return
input('1.按姓名删\n2.按学号删\n其他:返回\n请选择:')
if num == '1'
key = 'name'
value = input ('请输入要删除的学生的名字:')
elif num == '2'
key = 's_id'
value = input('请输入要删除的学生id:')
else:
return
students = list(filter(lambda s: s.get(key, '') == value, all_students))
if not students:
print('没有找到对应的学生')
return
for x, s in enuerate(students):
print('{x} 学号: {s_id}, 姓名: {name}, 性别: {gender}, 年龄: {age}, ☎: {tel}'.format(x=i, **s))
n = input('请输入需要删除的学生的标号(0~{}),q-返回:'.format(i) # 使用变量 i 有潜在风险
if not n.isdigit() or not 0 <= int(n) <= i:
print('输入的内容不合法')
return
# 将学生从all_students里删除
all_students.remove(students[int(n)])
y['all_student'] = all_students
file_manager.write_json(name + '.json', y)
def show_manager():
# print('显示管理页面')
content = file_manager.read_file('students_page.txt') % name
while True:
operator = input('请选择(1-5):')
if operator == '1':
add_student()
elif operator == '2':
show_student()
elif operator == '3':
modify_student()
elif operator == '4':
delte_student()
elif operator == '5':
break
else:
print('输入有误!')
model.py:
class Teacher(object):
def __init__(self, name, password):
import tools
self.name = name
self.password = tools.encrypt_password(password)
class Student(object):
def __init__(self, s_id, name, age, gender, tel):
self.s_id = s_id
self.name = name
self.age = age
self.gender = gender
self.tel = tel
tools.py:
import hashlib
def encrypt_password(passwd, x='afsoijweogj4wiu'):
h = hashlib.sha256()
h.update(passwd.encode('utf8')) # 123456afsoijweogj4wiu
h.update(x.encode('utf8'))
return h.hexdigest()
data.json:
数据集
此系统存在的问题:学生id的问题,应该是用学生id的最大数+1去补充,否则可能会出现id重复。
另外,后续会利用数据库来处理此类问题。