python - write login entry

Topic: write a login portal in python
requirement:

  1. Enter account password
  2. Login succeeded. Welcome message is displayed
  3. Enter the wrong password three times to lock the account

analysis:

  1. First, you need a file to save user information, including user name, password and whether the account is locked
  2. Secondly, according to the user name entered by the user, it is necessary to easily query whether the user exists in the file, if so, whether the user is locked, and how to judge whether the password matches.
  3. Finally, if you input the wrong password three times, you need to lock the user, and the locking information needs to be saved to the original file.

reference resources
https://www.cnblogs.com/elleblog/p/7747554.html

Self realization

  1. Knowledge points:
  • python's reading and writing of excel files;
  • The xlrd and xlutils modules can only handle xls class files can only be processed by openpyxl module xlsx class files;
  • Dictionary -- a keyword can correspond to multiple values
  1. thinking
  • Create an excel table (the suffix is. xlsx, so the module used this time is openpyxl). First save some user information as follows:

    It is worth noting that The lines of xlsx files start with 1 xls files start with 0
  • Load the file and establish a dictionary for user information. The user name is a keyword, and the corresponding values include the user's password, whether it is locked (1 yes, 0 no) and the user's line (here is to facilitate subsequent modification of the locked state)
  • User input account name
  • Check whether the keyword exists in the dictionary. If it does not exist, an error message will be prompted
  • If it exists, check the locking status of the user. If it is locked, you will be prompted
  • If it is not locked, you are prompted for a password
  • Check whether the passwords match
  • If it is correct, you will be prompted that the login is successful
  • After the number of errors reaches three, the locked information of the user is written to the source file and saved
  1. Detailed steps:
    ————Create a file to store user information -————

Path: ‪ D: \ bjpython \ Lianxi \ logintest \ userinfo \ userinfo xlsx
Content:

————Configuration environment and third-party packages -————

Tool: pycharm
Interpreter: Python 3 seven
Package: openpyxl

————Code part -————

Click to view the code
# Import module
import openpyxl
Click to view the code
# Load user information
    user_info_table = openpyxl.load_workbook(r"D:\BJpython\lianXi\logintest\UserInfo\UserInfo.xlsx") # The r before the path is to avoid the inconvenience caused by escape characters, so that you can find the target file according to the original string
    data = user_info_table.worksheets[0]
Click to view the code
# Establish a dictionary. Establish a dictionary based on the user information obtained above according to the user name. Each user name is a keyword, and its corresponding values include: password, whether it is locked (1 means locked) and the line
    user_info = {}
    for i in range(2, data.max_row+1):
        for j in range(2, data.max_column+1):
            user_info.setdefault(data.cell(i, 1).value, []).append(data.cell(i, j).value)
        user_info.setdefault(data.cell(i, 1).value, []).append(i)

    # Output and observe whether the dictionary is established correctly
    # print(user_info)
Click to view the code
# User input user name
    user_name = input("please input your username:")
Click to view the code
# Judge whether the user name is empty or wrong, or whether the user has been locked. If the user name is correct and not locked, start entering the password
    if user_name == "":
        user_name = input("please input correct username:\n")
    if user_name not in user_info.keys():
        print("your username is not correct!")
        return
    if user_info[user_name][1] == "1":
        print("Your login name is locked, please contact the service.")
    else:
        for wrong_time in range(0, 3):
            password = input("please input your password:")
            if password == str(user_info[user_name][0]):  #In order to maintain the same format on both sides of the equal sign, the password format is forcibly changed to str
                print('Login successfully!')
                return
            elif wrong_time == 2:   # If the password is entered incorrectly for three times, the account will be locked
             
                data.cell(user_info[user_name][2], 3, "1")
                user_info_table.save(r"D:\BJpython\lianXi\logintest\UserInfo\UserInfo.xlsx")
                # Prompt login locked
                print("Input wrong password 3 times, your login name is locked, please contact the service.")
                return

Original code (including the processing of. xls files)

Click to view the code
# -*- coding:utf-8 -*-
# Function of this Code: write login entry
# 1. Enter user name and password
# 2. Welcome message will be displayed after successful authentication
# 3. Lock after three wrong inputs
# Author: lm
# Date: January 16, 2022
# Knowledge points involved: excel table reading (xlrd), writing (xlwt, xlutils), dictionary establishment and addition of keyword values, and access
# But the excel file created is xlsx file, while xlrd and xlwt modules can only operate xls file xlsx files need openpyxl module

# import xlrd      # xlrd is used to read user information pre-existing in excel
# import xlwt
# from xlutils.copy import copy # xlutils.copy is used to transition to xlwt write function, that is, write content in excel table
import openpyxl
def Login():
    # Obtain user information. The form includes user name, password and whether it is locked
    # user_info_table = xlrd.open_workbook(r"D:\BJpython\lianXi\logintest\UserInfo\UserInfo.xlsx", formatting_info=True)
    # data = user_info_table.sheets()[0]

    user_info_table = openpyxl.load_workbook(r"D:\BJpython\lianXi\logintest\UserInfo\UserInfo.xlsx")
    data = user_info_table.worksheets[0]

    # Establish a dictionary. Establish a dictionary based on the user information obtained above according to the user name. Each user name is a keyword, and its corresponding values include: password, whether it is locked (1 means locked) and the line
    user_info = {}
    # for i in range(1,data.nrows):
    #     for j in range(1, data.ncols):
    #         user_info.setdefault(data.cell(i,0).value, []).append(data.cell(i, j).value)
    #     user_info.setdefault(data.cell(i,0).value, []).append(i)

    for i in range(2, data.max_row+1):
        for j in range(2, data.max_column+1):
            user_info.setdefault(data.cell(i, 1).value, []).append(data.cell(i, j).value)
        user_info.setdefault(data.cell(i, 1).value, []).append(i)

    # Output and observe whether the dictionary is established correctly
    # print(user_info)

    # User input user name
    user_name = input("please input your username:")

    # Judge whether the user name is empty or wrong, or whether the user has been locked. If the user name is correct and not locked, start entering the password
    if user_name == "":
        user_name = input("please input correct username:\n")
    if user_name not in user_info.keys():
        print("your username is not correct!")
        return
    if user_info[user_name][1] == "1":
        print("Your login name is locked, please contact the service.")
    else:
        for wrong_time in range(0, 3):
            password = input("please input your password:")
            if password == str(user_info[user_name][0]):  #In order to maintain the same format on both sides of the equal sign, the password format is forcibly changed to str
                print('Login successfully!')
                return
            elif wrong_time == 2:   # If the password is entered incorrectly for three times, the account will be locked
                # new_user_info_table = copy(user_info_table)
                # new_user_info = new_user_info_table.get_sheets(0)
                # new_user_info.write(user_info[user_name][2], 2, "1")
                # new_user_info_table.save(r"D:\BJpython\lianXi\logintest\UserInfo\UserInfo.xlsx")
                data.cell(user_info[user_name][2], 3, "1")
                user_info_table.save(r"D:\BJpython\lianXi\logintest\UserInfo\UserInfo.xlsx")
                # Prompt login locked
                print("Input wrong password 3 times, your login name is locked, please contact the service.")
                return

if __name__ == "__main__":
    Login()





Other references:
Copy module of xlutils in python
https://www.cnblogs.com/hls-code/p/14839840.html
openpyxl module
https://www.cnblogs.com/tonyxiao/p/14672521.html

20220116 I'm dying of my boyfriend lzy. He has been locked in the dormitory for more than a month. I don't know if he can go home for the new year. It hurts~
Learning is the only way to solve your worries.

Added by sotusotusotu on Mon, 17 Jan 2022 03:03:33 +0200