Application of Python decorator -- login authentication
編輯:Python
""" demand : Sign in CSDN After the success of the community , To access " Blog "、" Course "、" Question and answer " Such as the page Account file already exists csdn And account password : albert|123456 don|456 jack|789 """
# A dictionary that records a user's login status
user_status = {
'usname': None,
'status': False}
def get_userpwd():
user_dict = {
}
with open('csdn', encoding='utf-8', mode='r') as f:
for line in f:
user, pwd = line.strip().split('|')
user_dict[user] = pwd
return user_dict
def csdn_login():
userpwd_dict = get_userpwd()
count = 1
while count < 4:
username = input(' Please enter your user name :').strip()
password = input(' Please enter your password : ').strip()
if username in userpwd_dict and userpwd_dict[username] == password:
print(f' Login successful , Welcome {
username}')
user_status['usname'] = username
user_status['status'] = True
return True
else:
print(f' I'm sorry , The user name or password you entered is incorrect , Remaining opportunities {
3-count} Time !')
count += 1
return False
# Decorator , Only after successful login , To access
def csdn_decorator(func):
def inner(*args, **kwargs):
if user_status['status']:
ret = func(*args, **kwargs)
return ret
else:
if csdn_login():
ret = func(*args, **kwargs)
return ret
return inner
@csdn_decorator
def csdn_blog():
print(' Welcome to visit “ Blog ” home page !!!')
@csdn_decorator
def csdn_course():
print(' Welcome to visit “ Course ” home page !!!')
@csdn_decorator
def csdn_quest_ans():
print(' Welcome to visit “ Question and answer ” home page !!!')
# After successful login , To access the blog home page
csdn_blog()
# After successful login , To access the course home page
csdn_course()
# After successful login , To access the course home page
csdn_quest_ans()