簡體   English   中英

使用 python 創建登錄系統

[英]creating a login system with python

所以我是 python 的新手,並試圖創建一個簡單的登錄系統來注冊用戶和登錄,但我在密碼和用戶名驗證方面遇到了問題,下面是代碼(請注意,我已經將我的代碼划分為不同的模塊,因為我正在考慮實現將來:

register module
import re
def register():
    with open('username.txt', mode='a')as user_file:
        username = input('Enter Username : ')
        user_file.write(f"{username}\n")
    with open('password.txt', mode='a')as pass_file:
        password = input('Enter Password: ')
        pattern= re.compile(r'[a-zA-Z0-9@#!$%^&*]{8,}')
        if password==pattern.fullmatch(password):
            pass_file.write(f'{password}\n')
        else:
            print("your password should be atleast 8 characters long!")
login module
def login() :
    l_user = input('Username: ')
    l_pass = input('Password: ')
    with open('username.txt', mode='r')as user_file:
        for users in user_file:
            validate_u = user_file.readlines()
    with open('password.txt', mode='r')as pass_file:
        for passwords in pass_file:
            validate_p = pass_file.readlines()
    if l_user==validate_u and l_pass==validate_p:
        print('hello')
    else:
        print('login failed')
finally main module
import Enigma_Register
import Enigma_login

print('1-Login\n2-Register')
choice = int(input("enter choice: "))
if choice == 1:
    Enigma_login.login()

elif choice == 2:
    Enigma_Register.register()
    Enigma_login.login()
else:
    print('Invalid Choice!')

對於您的登錄 function,將最后四行替換為:

if l_user+"\n" in validate_u: #ReadLines() adds newlines
   user_num = validate_u.index(l_user+"\n")
   if l_pass+"\n" == validate_p[user_num]:
      print("Password correct!")
   else:
      print("Password incorrect!")
else:
   print("Cannot find your username!")

此外,user_file 中的for users in user_filefor passwords in pass_file是不必要的:只需將readlines()方法放在自己的位置上,沒有循環。

此外,將if password==pattern.fullmatch替換為if pattern.match(password)

我還建議您驗證密碼之前將文件寫入移動,否則可能會出現沒有密碼的“幽靈用戶名”,很容易導致問題; 或者您可以在password = input("Enter password: ")之后替換register() function 中的所有代碼

pattern = re.compile( [YOUR REGEX HERE] )
while not pattern.match(password):
  print("Your password is invalid.")
pass_file.write(f'{password}\n')
user_file.write(f'{username}\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM