Implementing business card management system with Python

Begin to change 2022-05-14 15:09:15 阅读数:845

implementingbusinesscardmanagementpython

Catalog

One 、 Title Description

Two 、 analysis

1、 analysis

2、 structure

        ① Encapsulate two classes

        ② Tool class

        ③ File management class

        ④ Home page class

        ⑤ Student management

3、 ... and 、 Source code

1、files_manager.py

2、index.py

3、model.py

4、student_manage.py

5、tools.py


One 、 Title Description

Data structure setting of student management system :

A student information corresponds to a dictionary

All students in the whole system : All students correspond to a list , The elements in the list are all dictionaries

The whole system : A dictionary , There is a in the dictionary key(all_student)

The corresponding value is all students ; This dictionary needs data persistence , Store data to json In file , The file name is the current login account name

{ 'all_student': [

                {'name': ' Zhang San ', 'age': 89, 'tel': '237837293'},

                {'name': ' Zhang San ', 'age': 89, 'tel': '237837293'},

                {'name': ' Zhang San ', 'age': 89, 'tel': '237837293'},

                {'name': ' Zhang San ', 'age': 89, 'tel': '237837293'} ],

'num': 4 }

Two 、 analysis

1、 analysis

        In the previous article, I wrote about the bank management system , Other systems are not much different from them in general logic , The difference lies in the ideological framework , The previous one was written in a .py In file , The function is realized by means of , This time the system will rise to a higher level , Applied to the idea of encapsulation , But it's also very simple .

2、 structure

        ① Encapsulate two classes

                Encapsulate the definitions of the two classes into a file , When you need it, you just need to import it ;

# -*- coding: utf-8 -*-
from tools import encrypt_password as encrypt
class Teach:
def __init__(self,name,password):
"""
Teachers log in to the student management system , Only static properties
:param name:
:param password:
"""
self.name = name
self.password = encrypt(password)
# For safety's sake , Imported an encrypted module , Encrypt password
# The encrypted password cannot be decrypted in reverse , Only when the same password calls the same function and the results are the same can it be regarded as a password box, etc
class Student:
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

        ② Tool class

That is, the class that encrypts the password , The call to password encryption is hashlib Module encryption

# -*- coding: utf-8 -*-
# Password encryption
import hashlib
def encrypt_password(password,salt='1234'):
"""
Cryptographic functions
:param password: password
:return: Encrypted password
"""
h = hashlib.sha256()
h.update(password.encode('utf-8'))
h.update(salt.encode('utf-8'))
return h.hexdigest()# return 16 Base number 

        ③ File management class

         Because the data needs to be managed persistently , That is to store data in a file , It also involves the operation of files ; As long as data is involved in the system, it will be used , Therefore, the encapsulation at this time greatly reduces the reuse rate of the code ;

        The file management class includes three methods : The first is to read the contents of ordinary files ; The second is to read JSON file ; The third is to write JSON file ;

        The difference between the first and the second is , The data in the first file reads out a string , Easy to operate , And the second one reads out JSON file , and JSON Files cannot be operated directly , Need to call JSON Module deserialization method , take JSON Convert format to string format

# -*- coding: utf-8 -*-
base_path = './files/'
def read_file(file_path):
"""
Read the contents of ordinary files
:param file_path: File path
:return: The contents of the document
"""
try:
with open(base_path + file_path,'r',encoding='utf-8') as f:
content = f.read()
return content
except FileNotFoundError as e:
print(' Failed to read the file. Please check the path ',e)
return ''
import json
def read_json(file_path,None_data=None):
"""
Read Json file
:param file_path: File path
:return: The contents of the document
"""
try:
with open(base_path + file_path,'r',encoding='utf-8') as f:
content = json.loads(f.read())
return content
except Exception as e:
# print(' Failed to read the file. Please check the path ',e)
return None_data
def write_json(file_path,data):
"""
write in json file
:param file_path: File path
:param data: Written data
:return: None
"""
with open(base_path+file_path,'w',encoding='utf-8') as f:
json.dump(data,f)
if __name__ == '__main__':
print(read_file('welcome.txt'))

        ④ Home page class

         The home page class defines three methods , The first way is : After the user enters the system , It will give users a welcome interface , Then let the user choose the next function , The welcome interface gives three options , Sign in 、 Register and exit

        The second method is the login function , First, from the database ( That is to get data from the file , What you get is a dictionary ) Get username , Then compare it with the user input , If it exists, enter the password , If it does not exist, remind the user to re-enter

        The third is the registration function , There are simple constraints on user names , After meeting the conditions , Then judge whether the data is in the database , If none of them are in , Registration is allowed , After the user name and password are qualified , Instantiate it to a teacher object , Then add the user name and password to the dictionary , Then write the dictionary to the file , Update the database

# -*- coding: utf-8 -*-
# The teacher completes the registration and login
# After successful login, select the menu
import files_maneger
import model
import student_manager
from tools import encrypt_password
USERS_FILE = 'teacherinfo.json'
# Variable A lowercase letter
# Constant Capitalization
# Sign in
def login():
all_user = files_maneger.read_json(USERS_FILE,{})# Load database, etc
username = input(' Please enter a user name ')
# Determine whether the user name has been registered
if username not in all_user:
print(' User name is not registered yet , Please re-enter ')
else:
password = input(' Please input a password :')
if all_user[username] == encrypt_password(password):
print(' Login successful ')
student_manager.USERNAME = username
student_manager.show_system()
return False
# register
def register():
while True:
username = input(' Please enter a user name ')
if 6 <= len(username) <= 30:
break
else:
print(' Incorrect user name length , Please re-enter ')
# Determine if the user name exists
all_user = files_maneger.read_json(USERS_FILE,{})
print(type(all_user))
if username in all_user:
print(' Registration failed , User name already exists ')
return
# If the length meets the requirements , The user name does not exist , Then let the user enter the password
while True:
password = input(' Please input a password ')
if 30>= len(password) >=6:
break
print(' Illegal password length , Please re-enter ')
# Create a teacher object
new_teacher = model.Teach(username,password)
all_user[new_teacher.name] = new_teacher.password
files_maneger.write_json(USERS_FILE,all_user)
def start():
content = files_maneger.read_file('welcome.txt')
while True:
print(content)
value = input(' Please enter the serial number of the operation ')
if value == '1':
login()
elif value == '2':
register()
elif value == '3':
print(' Quit successfully ')
exit()
else:
print(' Input error , Please re-enter ')
if __name__ == '__main__':
start()

        ⑤ Student management

         After successful login , In order to add, delete, modify and check students ;

        Add student :

         After successful login , Record the user name , Then open the corresponding file , Get the data of the students , The data is stored in the form of key value pairs , What we need is the value of the dictionary , That is to get through the key ; Then it is to build a student object according to the input student information , Then use magic method to store the object in the form of dictionary in the previously obtained student data list , Then corresponding to the previous key, it is stored in the dictionary , Last written to file , This completes the addition function

def add_studnet():
system_data = files_maneger.read_json(USERNAME+'.json',{})
all_student = system_data.get(ALL_STUDENT,[])
while True:
name = input(' Please enter the student's name ')
age = input(' Please enter the age of the student ')
gender = input(' Please enter the student's gender ')
tel = input(' Please enter the student's mobile phone number ')
# Create student id
count = system_data.get('num',0)
count +=1
s_id = 'stu'+str(count).zfill(4)# The length is 4, Front complement 0
# Create student objects
new_student = model.Student(s_id=s_id,name=name,age=age,gender=gender,tel=tel)
all_student.append(new_student.__dict__)
print(new_student.__dict__)
print(type(new_student.__dict__))
system_data[ALL_STUDENT] = all_student
system_data['num'] = count
# write file
#w Overwrite the original file
files_maneger.write_json(USERNAME+'.json',system_data)
print(' Add success ')
# Give a choice , Whether or not to continue
value = input('1 continue \n2 return ')
if value != '1':
break

        Delete students :

         There are two ways to delete students , One is logically deleted ( Copy the original data first , Then delete the data in the replication ), One is physical deletion ;

        The system provides two ways to delete , One is by name , One is according to the student number , The logic of the two is essentially the same , It's just that the values to be judged are different ;

        Because there may be students with the same information , So before deleting, store the student information of the same information , Then let the customer choose again , Then delete the data according to the serial number selected by the customer , Finally, write the deleted dictionary to the file , This completes the deletion function

def del_student():
# Load database information
system_data = files_maneger.read_json(USERNAME + '.json', {})
all_student = system_data.get(ALL_STUDENT, [])
del_students = []
# If there are no students Can't delete
if not all_student:
print(' No student information , Can't delete ')
return
print('1. Delete by name \n,2. Delete by student number \n other : return ')
choice = input(' Please select the method to delete ')
if choice == '1':
key = 'name'
value = input(' Please enter the name of the student you want to delete ')
elif choice == '2':
key = 's_id'
value = input(' Please enter the student number to be deleted ')
else:
return
# The above is just to select the deletion method , You also need to determine whether the student information
for stu in all_student:
if stu[key] == value:
del_students.append(stu)
if not del_students:
print(' No students found to delete ')
return
length = len(del_students)
for index,stu in enumerate(del_students):
print('{}.{}'.format(index+1,get_stu_message(stu)))
try:
choice = int(input(f' Please select the student number to delete 1~{length}:'))
except ValueError:
return
if not 1 <= choice <= length:
return
# Delete student information Physical delete
all_student.remove(del_students[choice - 1])
system_data[ALL_STUDENT] = all_student
files_maneger.write_json(USERNAME + '.json', system_data)
print(' Delete successful ')

        Find students :

The logic of finding students is the simplest , I will not introduce you

def find_student():
# Find a single
# Find all
system_data = files_manager.read_json(USERNAME + '.json', {})
all_student = system_data.get(ALL_STUDENT, [])
if not all_student:
print(' No student information , Cannot find ')
return
print('1. Find all the students 2. Check by name \n3. Check by student number \n other : return ')
choice = input(' Please select the way to find :')
if choice == '1':
for stu in all_student:
print(get_stu_message(stu))
elif choice == '2':
name = input(' Please enter the name of the student you want to find ')
flag = True
for stu in all_student:
if stu['name'] == name:
print(get_stu_message(stu))
flag = False
if flag:
print(' The student was not found ')
elif choice == '3':
s_id = input(' Please enter the student number you want to find ')
for stu in all_student:
if stu['s_id'] == s_id:
print(get_stu_message(stu))
break
else:
print(' The student was not found ')
else:
return 

        Revise students

         There are similarities between modifying student information and deleting student information , First, find the response data according to the student's information , And then operate on the data , The logic is similar

def edit_student():
# edit 1 Find out the students to edit 2 Edit student information
system_data = files_manager.read_json(USERNAME + '.json', {})
all_student = system_data.get(ALL_STUDENT, [])
if not all_student:
print(' No student information , Cannot edit ')
return
print('1. Find and edit by name \n2. Find and edit student information according to student number \n other : return ')
edit_students = []
choice = input(' Please select the way to edit :')
if choice == '1':
name = input(' Please enter the name of the student to edit ')
for stu in all_student:
if stu['name'] == name:
edit_students.append(stu)
if not edit_students:
print(' No information about the student to edit ')
return
# If there is student information , Put it in del_students
length = len(edit_students)
for index, stu in enumerate(edit_students):
print('{}.{}'.format(index + 1, get_stu_message(stu)))
try:
choice = int(input(f' Please select the student number to edit 1~{length}:'))
# You can only let the user re-enter the user name Gender Age cell-phone number
name = input(' Please enter the student's name :')
gender = input(' Please enter the gender of the student :')
age = input(' Please enter the age of the student :')
tel = input(' Please enter the student's phone number :')
# name
# gender
# age
# tel
except ValueError:
return
if not 1 <= choice <= length:
return
all_student[choice-1]['name'] = name
all_student[choice-1]['age'] = age
all_student[choice-1]['tel'] = tel
all_student[choice-1]['gender'] = gender
system_data[ALL_STUDENT] = all_student
files_manager.write_json(USERNAME + '.json', system_data)

3、 ... and 、 Source code

1、files_manager.py

# Here, you can read and write files
base_path = './myfile/'
def read_file(file_path):
"""
Read file contents
@param file_path: File path
@return: The contents of the document
"""
try:
with open(base_path + file_path, 'r', encoding='utf-8') as f:
content = f.read()
return content
except FileNotFoundError as e:
print(' Failed to read the file. Please check the path ', e)
return '' # Returns an empty string
import json
def read_json(file_path, None_data=None):
"""
Read json file
@param file_path: File path
@return: The contents of the document
"""
try:
with open(base_path + file_path, 'r', encoding='utf-8') as f:
content = f.read()
return json.loads(content)
except FileNotFoundError as e:
print(' Failed to read the file. Please check the path ', e)
return None_data # Return empty content
def write_json(file_path, data):
"""
write in json file
@param file_path: File path
@param data: Written data
@return: None
"""
with open(base_path + file_path, 'w', encoding='utf-8') as f:
json.dump(data, f)

2、index.py

# The teacher completes the registration and login
# After successful login, select the menu
import files_manager
import model
from tools import encrypt_password
import student_manage
import sys
USERS_FILE = 'teacherinfo.json'
# Variable A lowercase letter
# Constant Capitalization
def login():
all_user = files_manager.read_json(USERS_FILE, {}) # Load the database and wait for the user to enter the user name
username = input(' Please enter a user name :')
# Determine whether the user name has been registered
if username not in all_user:
print(' User name is not registered yet , Please re-enter ')
else:
password = input(' Please input a password :')
if all_user[username] == encrypt_password(password):
print(' Login successful ')
student_manage.USERNAME = username
student_manage.show_system()
return False
def register():
while True:
username = input(' Please enter a user name :')
if 6 <= len(username) <= 30:
break
print(' Illegal user name length , Please re-enter ')
# Determine if the user name exists
all_user = files_manager.read_json(USERS_FILE, {})
if username in all_user:
print(' Registration failed , User name already exists ')
return
# If the length meets the requirements and the user name does not exist , Then let the user enter the password
while True:
password = input(' Please input a password :')
if 30 >= len(password) >= 6:
break
print(' Illegal password length , Please re-enter ')
# Create a teacher object
new_teacher = model.Teacher(username, password)
all_user[new_teacher.name] = new_teacher.password
files_manager.write_json(USERS_FILE, all_user)
def start():
content = files_manager.read_file('welcome.txt')
while True:
value = input(content+'\n Please enter the serial number of the operation :')
if value == '1':
login()
elif value == '2':
register()
elif value == '3':
print(' Quit successfully ')
# exit()
sys.exit(0) # Quit the whole program
else:
print(' Input error , Please re-enter ')
if __name__ == "__main__":
start()

3、model.py

# Put all the classes in this
from tools import encrypt_password
class Teacher:
'''
The classroom is used to log in to the student management system Only static properties
'''
def __init__(self, name, password) -> None:
self.name = name
self.password = encrypt_password(password)
class Student:
def __init__(self, s_id, name, age, gender, tel) -> None:
self.s_id = s_id
self.name = name
self.age = age
self.gender = gender
self.tel = tel

4、student_manage.py

# The student information is analyzed Add or delete check change
import files_manager
import model
USERNAME = ''
ALL_STUDENT = 'ALL_STUDENT'
NUM = 'NUM'
def add_student():
# print(123)
# Every time students operate, they must first link to the database And get the information of the database to
system_data = files_manager.read_json(USERNAME + '.json', {})
all_student = system_data.get(ALL_STUDENT, [])
while True:
name = input(' Please enter the student's name :')
age = input(' Please enter the age of the student :')
gender = input(' Please enter the gender of the student :')
tel = input(' Please enter the student's mobile phone number :')
# Create student id
count = system_data.get(NUM, 0)
count += 1
s_id = 'stu' + str(count).zfill(4) # The length is 4 String , Front complement 0
# Create student objects
new_student = model.Student(s_id=s_id,
name=name,
age=age,
gender=gender,
tel=tel)
all_student.append(new_student.__dict__)
system_data[ALL_STUDENT] = all_student
system_data[NUM] = count
# write file
# w Overwrite source file
files_manager.write_json(USERNAME + '.json', system_data)
print(' Add success ')
# Give a choice
value = input('1 continue \n2 return ')
if value != '1':
break
# Physical delete Logical deletion
def del_student():
# Load database information
system_data = files_manager.read_json(USERNAME + '.json', {})
all_student = system_data.get(ALL_STUDENT, [])
# If there are no students Can't delete
if not all_student:
print(' No student information , Can't delete ')
return
print('1. Delete by name \n2. Delete by student number \n other : return ')
del_students = []
choice = input(' Please select the method to delete ')
if choice == '1':
key = 'name'
value = input(' Please enter the name of the student you want to delete ')
elif choice == '2':
key = 's_id'
value = input(' Please enter the student number to be deleted ')
else:
return
# The above is just to select the deletion method , You also need to judge whether there is student information
for stu in all_student:
if stu[key] == value:
del_students.append(stu)
if not del_students:
print(' No students found to delete ')
return
# If there is student information , Put it in del_students
length = len(del_students)
for index, stu in enumerate(del_students):
print('{}.{}'.format(index + 1, get_stu_message(stu)))
try:
choice = int(input(f' Please select the student number to delete 1~{length}:'))
except ValueError:
return
if not 1 <= choice <= length:
return
# Delete student information Physical delete
all_student.remove(del_students[choice - 1])
system_data[ALL_STUDENT] = all_student
files_manager.write_json(USERNAME + '.json', system_data)
print(' Delete successful ')
def get_stu_message(stu):
return ' The student number is {}, full name {}, Gender is {}, Age is {}, cell-phone number :{}'.format(stu['s_id'], stu['name'],
stu['gender'], stu['age'],
stu['tel'])
# lookup
def find_student():
# Find a single
# Find all
system_data = files_manager.read_json(USERNAME + '.json', {})
all_student = system_data.get(ALL_STUDENT, [])
if not all_student:
print(' No student information , Cannot find ')
return
print('1. Find all the students 2. Check by name \n3. Check by student number \n other : return ')
choice = input(' Please select the way to find :')
if choice == '1':
for stu in all_student:
print(get_stu_message(stu))
elif choice == '2':
name = input(' Please enter the name of the student you want to find ')
flag = True
for stu in all_student:
if stu['name'] == name:
print(get_stu_message(stu))
flag = False
if flag:
print(' The student was not found ')
elif choice == '3':
s_id = input(' Please enter the student number you want to find ')
for stu in all_student:
if stu['s_id'] == s_id:
print(get_stu_message(stu))
break
else:
print(' The student was not found ')
else:
return
def edit_student():
# edit 1 Find out the students to edit 2 Edit student information
system_data = files_manager.read_json(USERNAME + '.json', {})
all_student = system_data.get(ALL_STUDENT, [])
if not all_student:
print(' No student information , Cannot edit ')
return
print('1. Find and edit by name \n2. Find and edit student information according to student number \n other : return ')
edit_students = []
choice = input(' Please select the way to edit :')
if choice == '1':
name = input(' Please enter the name of the student to edit ')
for stu in all_student:
if stu['name'] == name:
edit_students.append(stu)
if not edit_students:
print(' No information about the student to edit ')
return
# If there is student information , Put it in del_students
length = len(edit_students)
for index, stu in enumerate(edit_students):
print('{}.{}'.format(index + 1, get_stu_message(stu)))
try:
choice = int(input(f' Please select the student number to edit 1~{length}:'))
# You can only let the user re-enter the user name Gender Age cell-phone number
name = input(' Please enter the student's name :')
gender = input(' Please enter the gender of the student :')
age = input(' Please enter the age of the student :')
tel = input(' Please enter the student's phone number :')
# name
# gender
# age
# tel
except ValueError:
return
if not 1 <= choice <= length:
return
all_student[choice-1]['name'] = name
all_student[choice-1]['age'] = age
all_student[choice-1]['tel'] = tel
all_student[choice-1]['gender'] = gender
system_data[ALL_STUDENT] = all_student
files_manager.write_json(USERNAME + '.json', system_data)
def show_system():
content = files_manager.read_file('stuinfo.txt') % USERNAME
while True:
print(content)
value = input(' Please select the operation to be performed ')
if value == '1':
add_student()
elif value == '2':
find_student()
elif value == '3':
edit_student()
elif value == '4':
del_student()
elif value == '5':
return
else:
print(' Input error , Please re-enter ')

5、tools.py

# Encryption of passwords
import hashlib
def encrypt_password(password, salt='xiaoyuaoyyds'):
"""
Cryptographic functions
@param password: password
@return: Encrypted password
"""
h = hashlib.sha256()
h.update(password.encode('utf-8'))
h.update(salt.encode('utf-8'))
return h.hexdigest() # Return hexadecimal
# Send a text message
# Send E-mail

版权声明:本文为[Begin to change]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/134/202205141443436417.html