0%

第四周-作业

exercise6:装饰器的使用

user-credentials.txt内容

1
2
3
4
{"name":"xiaoming", "password":"123"}
{"name":"xiaowang", "password":"321"}
{"name":"xiaofang", "password":"432"}
{"name":"xiaobai", "password":"111"}

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import json

def read_user_credentials(file_path):
credentials = []
with open(file_path, 'r') as file:
for line in file:
user_info = json.loads(line.strip())
credentials.append(user_info)
return credentials

def authentication_required(func):
authenticated = False

def wrapper(*args, **kwargs):
nonlocal authenticated
if not authenticated:
username = input("Enter your username: ")
password = input("Enter your password: ")
user_credentials = read_user_credentials("user_credentials.txt")
for user_info in user_credentials:
if user_info.get('name') == username and user_info.get('password') == password:
authenticated = True
print("Authentication successful!")
break
else:
print("Authentication failed. Please try again.")
return
return func(*args, **kwargs)

return wrapper

@authentication_required
def function1():
print("This is function 1.")

@authentication_required
def function2():
print("This is function 2.")

if __name__ == "__main__":
function1()
function1()

output

1
2
3
4
5
6
Enter your username: xiaoming
Enter your password: 123
Authentication successful!
This is function 1.
This is function 1.