Home >Backend Development >Python Tutorial >Detailed explanation of the specific steps for writing a login window

Detailed explanation of the specific steps for writing a login window

PHP中文网
PHP中文网Original
2017-06-20 13:47:461600browse

Ideas:

1. Reference model. For this assignment, I referred to the login authentication process of Linux and the locking rules such as online banking, Alipay, etc.;

1) The authentication process refers to Linux login: after you enter the username and password, verify whether the username exists and whether the user is locked, and then verify whether the password is correct. If the verification fails, it will only tell you that the verification failed, not Tell you whether the user name or password is wrong, which increases the difficulty of brute force cracking;

2) Regarding the counting and locking of incorrect times, I refer to This is what banks and Alipay do, that is, they only care about how many times you entered incorrectly, and don’t care how many times you entered incorrectly. That is to say, if you enter incorrectly twice, the third time If you enter correctly, the previous count is not cleared, that is, you entered 1,000 times today and lost 997 times correctly, but only entered incorrectly 3 times. Sorry, you still have to lock it. And the three incorrect entries do not have to be consecutive. It will be locked after three incorrect inputs three times.

## 2. Regarding the saving of

count and status, I consider persisting it through files . The accumulation and locking of each incorrect number of inputs are saved. in the file, although this increases the file operation, it ensures the reliability of the program. In this way, the program exits and the count is still valid. The file type is as follows:

alex sb lock 3

Tom 666 unlock 0 geng 888 unlock 2

The first column is the user name, the second column is the password, the third column is the user status (lock means locked, unlock means not locked), and the fourth column is the number of logins (in fact, the number of logins only needs to be increased by one when the error is made, no Don't worry about it when it's wrong).

##The code is as follows:

           with open(filename,)           key,values                           lines =                print(             f.write( .join(lines) +                           values.insert(             f.write( .join(values) +   # messages = {:[,,],:[,,],:[,, # write_file(messages,   __name__ ==      active =               username = input(         users_dict = {}     #用户字典,用于存放用户的信息,键-用户名,值-         with open(,)              lines =              line                  user_list =                 users_dict[user_list[]] = user_list[           username               users_dict[username][] ==                  print(                                (users_dict[username][]) <                      user_pwd = input(                      users_dict[username][] ==                         print(                                               (users_dict[username][]) !=                              print( % ( - (users_dict[username][                         users_dict[username][] = (users_dict[username][]) +                                        print(                     users_dict[username][] =                      users_dict[username][] =                      write_file(users_dict,         elif username ==                         print()
运行结果如下:
请输入你的用户名(输入quit退出):tom
请输入密码:22
还有2次机会,用户将被锁定!
请输入密码:22
还有1次机会,用户将被锁定!
请输入密码:22
对不起,您输入的次数过多,你的用户名已经被锁定,请联系管理员!
请输入你的用户名(输入quit退出):alex
您输入的用户名已经锁定,请联系管理员!

Actually The operation of files is essentially the operation of string lists, dictionaries, file operations, and the method of reading files. Readlines() reads and stores them in a list line by line, and uses dict (dictionary) to record user information. String splicing (join) method, (" ".join(list)), strings and lists are spliced ​​to form a new string. In fact, the essence of strings stored in Python is in the form of lists. Storage, splicing between lists, list.extend(list), splicing between lists.

Code description:

1. Two contents not covered in today’s course are used here: dictionaries and functions to convert user information into dictionaries The reason for saving in this way is to determine whether the user name exists. When reading the file, the user name is directly used as a key of the dictionary, and other information is used as the value of the dictionary in one-to-one correspondence with the key. In this way, only the user name is needed to determine whether the user name exists. Just use the in member operator to judge;

2. The 61st and 62nd lines of the code complete the process of turning the file into a dictionary.

# Original Zhang Xiaoyu code example:

#!/usr/bin/env python3
# coding:utf-8'''Created on: 2015年12月29日

@author: 张晓宇

Email: 61411916@qq.com

Version: 1.0Description: 输入用户名密码,认证成功显示欢迎信息,认证失败,输错三次后锁定

Help:'''import os
# 定义用户信息写入函数,用于把用户信息写回文件
def write_to_account_file(accounts,account_file_path):"""accounts是一个用户信息字典,目的是把变更过的信息写入文件中"""account_file = open(account_file_path,"w")for key,val in accounts.items():
        line = []
        line.append(key)
        line.extend(val)
        print(" ".join(line))      #字符串与列表拼接,目的是实现列表中每个元素加空格生成一个字符串如a b c d格式
        account_file.write(" ".join(line) + "\n")    #往文件中添加信息
    account_file.close()   #直接打开文件的时候一定要记得关闭文件,以免文件休息丢失if __name__ == '__main__':'''    @parameters:
        account_file_path:账户文件
        password_col_num:账户文件中密码所在的列(从0开始)
        status_col_num:账户文件中账户状态所在的列(从0开始)
        error_count_num:账户文件中输入错误次数所在的列(从0开始)
        app_info:系统信息,用户启动应用后的输出
        welcome_msg:用户成功登录后的信息'''    account_file_path = 'account.db'password_col_num = 1status_col_num = 2error_count_num = 3app_info = '''    +---------------------------------+
    | Welcome to gcx system           |
    | Version:2.0                     |
    | Author:zhuzhu                   |
    +---------------------------------+'''    welcome_msg = "Welcome %s,authentication is successful!"if os.path.exists(account_file_path):    #os.path.exists()判断文件是否存在,返回布尔值
    # 判断账户文件是否存在
        account_file = open(account_file_path,"r")else:
        #文件不存在,看系统是否有误
        print("Error:Account file 'account.db' is not exit,please check!")
        exit(1)

    #读账户文件
    accounts = {}for line in account_file.readlines():   #按行读取文件
        account = line.strip().split()      #清楚空格后进行分列,生成一个列表
        accounts[account[0]] = account[1:]"""把列表中的第一个元素(用户名)当做键,用户的其他信息当做值,组成键值对存放在字典中""""""account[0]键,account[1:]是值"""account_file.close()    #关闭文件
    flag = Truewhile flag:
        print(app_info)
        #输入用户名
        username = input("Username(Enter quit to exit): ").strip()
        #判断用户是否输入的为quitif username == "quit":
            #是则退出循环,程序结束breakpassword = input("Password: ").strip()
        #判断用户名是否存在if username not in accounts.keys():
            #不存在提示错误信息并退出当前循环让用户重新输入
            print("Error:Username or Password it is error!")continue     #结束本次循环,让用户再次输入用户名和密码,继续执行下一次循环if accounts[username][status_col_num - 1] == "lock":
            #如果被锁定退出当前循环让用户重新输入
            print("Error:Account is locked.Please contact the administrator!")continue    #跳过本次循环,让用户重新输入进行验证,这个可以避免很多缩进,能够继续执行下一次
        #判断用户密码是否正确if password == accounts[username][password_col_num - 1]:
            #正确显示欢迎信息
            print(welcome_msg %username)breakelse:
            #用户密码不正确的情况
            #提示用户名或密码错误
            print("Error:Username or Password it is error!")
            #输入错误次数加1
            accounts[username][error_count_num - 1] = str(int(accounts[username][error_count_num - 1]) + 1)
            #判断是否已经达3次if int(accounts[username][error_count_num - 1 ]) == 3:
                #如果输入错误达到3次
                #提示账户将被锁定
                print("Error: This account will be locked,Please contact the administrator!System will be exit!")
                #将用户状态改为lock并写入文件
                accounts[username][status_col_num - 1] == "lock"write_to_account_file(accounts,account_file_path)breakwrite_to_account_file(accounts,account_file_path)

Highlights in the above code:

(1) continue: End this loop. The code after continue will not be executed to achieve the purpose of allowing the user to input again. Many The web page allows users to keep typing until the user either chooses to register or close the web page;

(2) The document is relatively standardized and has explanations;

(3) The file is read line by line, and then written to the file line by line. The knowledge of lists and dictionaries must be used in the modification process;

(4) " ".join(list) splicing of strings and lists to generate new strings;

(5) split() string splitting; extend() between lists splicing.

The above is the detailed content of Detailed explanation of the specific steps for writing a login window. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn