用Python實現用戶登錄接口

項目需求描述:要求用戶輸入用戶名和密碼,認證成功後顯示歡迎信息,如果連續輸錯三次密碼則鎖定該用戶。


邏輯流程圖:

wKiom1Qys9DAAR9AAAGWHQ5vSb4391.jpg


實現代碼:

#!/usr/bin/env python
import sys

account_file = 'account.txt'
lock_file = 'lock.txt'

# put accounts in a list
fh_account = open(account_file)
account_list = fh_account.readlines()
fh_account.close()

# every account has 3 chances of attempt at the beginning
retry_count = {}
for line in account_list:
    line = line.split()
    retry_count[line[0]] = 3

while True:
    # put locked accounts in a list
    fh_lock = open(lock_file)
    lock_list = []
    for i in fh_lock.readlines():
        line = i.strip('\n')
        lock_list.append(line)
    fh_lock.close()

    # handle the username and password empty issue
    username = raw_input('Username: ').strip()
    if len(username) == 0:
        print '\033[31;1mUsername should not be empty !\033[0m'
        continue
    password = raw_input('Password: ').strip()
    if len(password) == 0:
        print '\033[31;1mPassword should not be empty !\033[0m'
        continue

    # authentication part
    if username in lock_list:
        print "\033[31;1mSorry, '%s' is locked already !\033[0m" % username
        continue
    if not retry_count.has_key(username):   # inexistent account
        retry_count[username] = 3
    for line in account_list:
        line = line.split()
        if username == line[0] and password == line[1]: # authentication pass
            retry_count[username] = 3       # reset retry times for this account
            sys.exit('\033[32;1mWelcome %s login my system !\033[0m' % username)
    else:                                   # authentication failed
        print '\033[31;1mWrong username or password !\033[0m'
        retry_count[username] -= 1
        if retry_count[username] > 0:
            print '\033[31;1mYou have %d more chances !\033[0m' % retry_count[username]
        else:                               # no more chance of attempt
            fh = open(lock_file, 'a')
            fh.write('%s\n' % username)
            fh.close()
            print "\033[31;1mSorry, '%s' is locked !\033[0m" % username


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章