English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example Explanation of Python User Management System

I have learned Python for so long, and this is the first time I have written so much code (I admit that I only have300+ lines, there are a lot of repeated code, I admit I am really bad), but it's also not easy

Custom function+Decorators, a function written for each module

Many places can use decorators (the logic is not following, some places are not used), including double decorators (I don't know), many places need optimization, too much repeated code

I still bring out my flowchart, although it looks worse than the last one, but I also did it for an hour, it's not easy!

It seems pretty ugly (I can't draw, but I will definitely try harder next time)

User file:

The file name is: user.txt

1Represent the administrator user

2Represents a normal user

smelond|admin|[email protected]|1
admin|admin|[email protected]|2
qwe|qweasd|[email protected]|2

Code (this program still has many bugs):

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# File_type:User management program, decorator version, multi-functional
# Filename:user_manage_program.py
# Author:smelond
import os
os.system("cls") # Clear screen in windows
COUNT = 0 # Counter
WHETHER_LOGIN = {"is_login": "error"} # Used to determine if a user is logged in
USER_LIST = [] # List to store current user information
def register_function(): # Registration function (all registrations call this function)
 count = 3 # Counter, serves as a prompt to the user
 for i in range(3】: # Loop3times
 print("User registration 【You only have3times, you still have 【%s】times left".center(8(0, "=") % count) # Output prompt
 count -= 1 # Decrease by1
 username = input("请输入用户名:")
 while True:
  passwd = input("请输入密码:")
  if len(passwd) >= 5:
  break
  else: # If the input password is less than5, digits, proceed downward
  print("Please enter a password greater than5passwords) # Enter a password with more than
  input_passwd = input("【1:Continue input;2:Return to the previous step】)
  if input_passwd == "1:
   pass
  else:
   main()
 while True:
  email = input("Please enter email: ")
  email_count = email.count("@") # Check if the input email contains '@',
  # print(email_count) # Return1represents that there is a '@'
  if email_count == 1:
  break # If there is an '@' symbol, it means the email input is correct, exit the current loop
  else:
  print("Please enter the correct email")
  input_email = input("【1:Continue input;2:Return to the previous step】)
  if input_email == "1:
   pass
  else:
   main()
 register_user = [username, passwd, email, "2"] # Place our input username, password, and email into a list, a normal user, so we added a2
 with open("user.txt", "r") as user:
  for line in user:
  f_user_list = line.strip("\n").split("|")
  if register_user[0] == f_user_list[0]:
   print("The username has already been registered")
   break
  if register_user[2] == f_user_list[2]: # Judge whether the email and username we input already exist
   print("The email has already been registered")
   break
  else: # Next, after passing the above filter, start writing our registration information to the database (I always feel there is a bug above)
  user_write = "|".join(register_user) # Use the join method to convert this list to be separated by |
  # open_user = open("user.txt", "a") # Write in append mode
  # open_user.write("\n" + user_write)
  # open_user.close() # Remember to close
  with open("user.txt", "a") as f:
   f.write("\n" + user_write) # Same method as above, this does not need to close the file
  print("Registration successful")
  user_write = """Username: [%s]; Password: [%s]; Email: [%s]""" \
    % (register_user[0], register_user[1], register_user[2]) # Prompt information for successful registration
  return user_write # Return prompt information
def outer(func): # Decorator used to manage interfaces
 def inner(*args, **kwargs):
 if WHETHER_LOGIN["is_login"] == "success" and USER_LIST[3] == "1: # Why do we need to quote it? Because the list stores strings, not integers
  r = func() # Execute the function passed in
  return r # Return
 elif WHETHER_LOGIN["is_login"] == "success" and USER_LIST[3] == "2: # Prompt that the user does not have sufficient privileges and return to the main function if it is a regular user
  print("\nThe current user is a regular user [%s], and does not have sufficient privileges" % USER_LIST[0])
  main()
 else:
  print("\nNo user is currently logged in, please log in and try again...") # Otherwise, it means the user is not logged in
  main()
 return inner
def user_login(func): # Decorator to check if the user is logged in
 def inner(*args, **kwargs):
 if WHETHER_LOGIN["is_login"] == "success": # Check if logged in
  r = func()
  return r # If already logged in, return to the original function
 else:
  user_no = input("Please log in again【1:User login;2:Return】:")
  if user_no == "1:
  login()
  else:
  print("返回成功")
  main()
 return inner # Be sure to return an inner here, otherwise the inner above will not execute. Do not add parentheses at the end, as adding them is equivalent to calling this function
def exit_login(): # 6Logout
 global USER_LIST
 if USER_LIST:
 quit_login = input("The current user is【%s】,are you sure you want to logout【Y/N】:" % USER_LIST[0])
 # if quit_login == "Y" or quit_login == "y" or quit_login == "yes":
 if quit_login in ("Y", "y", "yes", "yES", "yeS", "yEs", "YES", "Yes", "YEs"): # If quit_login meets one of the conditions, continue execution
  WHETHER_LOGIN["is_login"] = "error"
  USER_LIST = [] # Directly clear the list to its initial state, not sure if this method is good, but it seems to work
 elif quit_login in ("N", "n", "No", "nO", "NO"):
  print("Logout failed")
 else:
 print("No user is logged in...")
def verifi_passwd():
 with open("user.txt", "r") as old_user: # Open the 'user.txt' file in read mode
 lines = old_user.readlines() # Read the entire file at once, which does not seem to be a good approach
 flag = True
 cout = 3
 while flag:
 cout -= 1
 user_info = input("Please enter the username:")
 if user_info == "": # Check if a string is entered
  print("You have not entered any user...\n")
  manage()
 for line in lines:
  user_all_info = line.strip("\n").split("|")
  if user_info == user_all_info[0]:
  current_user = user_all_info # If the input user matches the user in the user file, then write all his information into a new list
  flag = False
 if cout == 0:
  print("However, you may not know which users there are, hurry up and check it out...")
  manage()
 lines_user = [lines, current_user]
 return lines_user
def user_info_func(username, password_or_power, user_info, lines): # The types of several incoming parameters are: username, password or user permission, the position of the user list to be modified, and the content of the file to be cycled through
 new_user_info = username.copy() # Copy username to new_user_info
 new_user_info[user_info] = password_or_power # Change the new user password to the new password entered
 username = "|".join(username) # Convert the list to content that the database can recognize
 new_user_info = "|".join(new_user_info)
 # print(username, new_user_info)
 with open("user.txt", "w") as new_user: # Open the 'user.txt' file in write mode
 for line in lines: # Loop through the entire file and print
  if username in line: # If the returned user information is in the returned file
  line = line.replace(username, new_user_info) # Replace the old user information with the new user information
  new_user.write(line) # Write to file
 print("Modified successfully") # Prompt information
@outer # Call the decorator
def manage(): # 5User Management Interface
 while True:
 print("User Management Interface【Welcome Admin [%s】".center(69, "=") % USER_LIST[0])
 print("1:查看所有用户;2、添加新用户;3:删除用户;4:修改用户密码;5:升级用户权限;6:退出用户管理
 user_input = input("请输入对象序号:")
 if user_input == "1: # View user information
  print("\n" + "-" * 80) # Print80个-
  with open("user.txt", "r") as user_info:
  for line in user_info:
   user_list = line.strip("\n").split("|") # Remove the default \n and | and convert it to a list type
   if user_list[3] == "1:
   user_rights = "Administrator User" # If the last number of the user is equal to1representing an administrator
   else:
   user_rights = "Ordinary User" # Otherwise, it is an ordinary user
   ordinary_user = """Username[%s]\tPassword[%s]\tEmail[%s]\tUser Level[%s]""" \
     % (user_list[0], user_list[1], user_list[2], user_rights) # There is a default newline character in the middle
   print(ordinary_user)
  print("-" * 80 + "\n")
 elif user_input == "2:
  while True:
  ret = register_function() # Call the registration function
  print(ret) # Output the return value
  break # Exit the current while loop
 elif user_input == "3:
  flag = "error" # Default is no user (for a prompt function)
  del_user = verifi_passwd()[1][0] # Get the second value returned by the function
  print("\033[1;31mThe user to be deleted is: \033[0m", del_user)
  with open("user.txt", "r") as old_user: # Open the 'user.txt' file in read mode
  lines = old_user.readlines() # Read the entire file at once, which does not seem to be a good approach1
  with open("user.txt", "w") as new_user: # Open the 'user.txt' file in write mode
  for line in lines: # Iterate over each line of the collected text
   if line.startswith(del_user): # Check if the user we entered is in the database (starting with the entered username)
   flag = "success"
   continue
   new_user.write(line)
  if flag == "success": # Prompt success
   print("Deleted successfully")
  else:
   print("This user does not exist...") # If the input is a space or some non-existent users, prompt that this user does not exist
   continue
 elif user_input == "4:
  ret = verifi_passwd() # Get the return value of the function
  lines = ret[0] # Get the entire file content returned
  username = ret[1] # Get the returned users who need to change their password
  new_password = input("Please enter the new password for the user:")
  if len(new_password) < 5: # Determine if the length of the entered password is greater than or equal to5digits
  error_prompt = input("The length of the password you entered is less than ")5digits, since you are an administrator, enter Y to continue: ").strip("") # Remove the spaces
  If error_prompt is not in ("y", "Y"), # If the input value is not y or Y, exit directly
   print("Exit...")
   continue
  user_info_func(username, new_password, 1, lines) # Pass actual parameters to the function,1The position in the list represents the user's new password
 elif user_input == "5]: # This part is basically similar to the above part, in fact, it can be written as a function to call
  ret = verifi_passwd()
  lines = ret[0]
  username = ret[1] # Get all information of the input user
  new_power = input("Enter Y to upgrade user privileges:")
  if new_power not in ("y", "Y"):
  print("Input error...")
  break
  user_info_func(username, "1, 3, lines) # Pass actual parameters: username, permission (1Represents an admin), position, loop file content
 elif user_input == "6:
  print("Return to the previous level!!!")
  main()
 else:
  print("Input error")
@user_login # Call the decorator
def see(): # 4Query the basic information of the current user
 if USER_LIST[3] == "1]: # It is defined in the database1Represents an admin user,2Represents a normal user
 user_level = "Admin user"
 else:
 user_level = "Normal user"
 user_see = """
 ----------------------------------------
 Username: 【%s】
 Password: 【%s】
 Email: 【%s】
 User level: 【%s】
 ----------------------------------------
 """ % (USER_LIST[0], USER_LIST[1], USER_LIST[2], user_level) # A simple formatted output
 print(user_see)
def error_password():
 counter = 3
 while True:
 counter -= 1
 if counter == 0:
  print("You have entered the wrong password too many times, the program will automatically return...")
  main()
 else:
  print("The passwords entered twice are not the same...")
  continue
@user_login # Call the decorator
def alter(): # 3Modify password
 print("The current user is: 【%s】" % USER_LIST[0])
 while True:
 old_user_password = input("Please enter the current user's old password: ")
 if old_user_password == USER_LIST[1]:
  flag = True
  count = 3
  while flag:
  count -= 1
  new_user_password = input("Please enter the current user's\033[1;31mNew password\033[0m: ) # Add color to the new password font
  new_user_password1 = input("Re-enter the current user's\033[1;31mNew password\033[0m: )
  if len(new_user_password) >= 5:
   flag = False
  elif count == 0:
   print("Invalid input multiple times, the program will automatically return...")
   main()
  else:
   print("Invalid input, please enter a password greater than5passwords) # Enter a password with more than
  if new_user_password == new_user_password1: # Check if the two entered passwords are equal
  with open("user.txt", "r") as user_info: # Open this file in read mode
   old_user_info = "|".join(USER_LIST) # Get the previous old information
   for line in user_info: # Output each line obtained
   if USER_LIST[0] in line: # Find the current logged-in user's username
    USER_LIST[1] = new_user_password1 # If found, re-add the new password to our global user information list
    new_user_info = "|".join(USER_LIST) # Convert the content of the user information list into the format used in the user database (new user information)
    # print(new_user_info)
    # print(old_user_info)
    break # Exit the current loop
  with open("user.txt", "r") as old_user: # Open the 'user.txt' file in read mode
   lines = old_user.readlines() # Read the entire file at once, which does not seem to be a good approach
  with open("user.txt", "w") as new_user: # Open the 'user.txt' file in write mode
   for line in lines: # Iterate over each line of the collected text
   if old_user_info in line: # Check if the old user information is present in the file
    line = line.replace(old_user_info, new_user_info) # Replace old user information with new user information if it exists
   new_user.write(line) # Then write it to the file
  print("修改成功√")
  break # Break after completion
  else: # Two inputs are not equal
  print("两次输入的密码不相同,程序自动返回。。。")
  main()
 else: # Current user password input error
  print("当前用户密码输入错误,程序自动返回。。。")
  main()
def register(): # 2用户注册
 if WHETHER_LOGIN["is_login"] == "success":
 quit_login = input("无法注册用户,请退出登录后重试【1: Exit login;2:返回上一步】:")
 if quit_login == "1:
  exit_login() # Jump to the user exit function
 elif quit_login == "2:
  print("返回成功")
 elif WHETHER_LOGIN["is_login"] == "error":
 ret = register_function() # Call the registration function
 print(ret) # Output the returned value
def login(): # 1用户登录
 print("用户登录".center(82, "="))
 username = input("请输入用户名:")
 passwd = input("请输入密码:")
 with open("user.txt", "r") as user:
 for line in user:
  f_user_list = line.strip("\n").split("|") # Remove the default newline and | from each line, and convert it to a list and assign it to f_admin_list
  if f_user_list[0] == username and f_user_list[1] == passwd:
  print("登录成功")
  global USER_LIST
  USER_LIST = f_user_list # Place the current line obtained into the user information list
  WHETHER_LOGIN["is_login"] = "success" # Set the value of is_login to success upon successful login
  WHETHER_LOGIN["is_user"] = username # Put the logged-in user into the dictionary for easy later lookup
  # print(USER_LIST)
  return f_user_list
 else:
  print("Login failed")
def main():
 while True:
 global COUNT
 COUNT += 1
 print("User Management System".center(80, "*) + "\n")
 print("1、User login;2: User registration;3: Change password;4: User information;5: User management;6: Exit login;7: Exit program)
 inp = input("Please enter the number: ")
 if inp == "1:
  if USER_LIST:
  if USER_LIST[3] == "1:
   print("The current user is the administrator: [%s], cannot continue to log in" % USER_LIST[0])
  else:
   print("The current user is [%s], cannot continue to log in" % USER_LIST[0])
  else:
  login()
 elif inp == "2:
  register()
 elif inp == "3:
  alter()
 elif inp == "4:
  see()
 elif inp == "5:
  manage()
 elif inp == "6:
  exit_login()
 elif inp == "7:
  exit("Program has exited!!!")
 else:
  if COUNT == 3:
  exit("Input error times too many, program will exit automatically...")
  else:
  print("Input error, please enter again...\n")
  continue
main()

This is the full content of the example explanation of the python user management system shared by the editor. I hope it can provide a reference for everyone, and also hope everyone will support and cheer for the tutorial.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like