程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

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()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved