-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11x-using_errors.py
More file actions
120 lines (82 loc) · 2.56 KB
/
Copy path11x-using_errors.py
File metadata and controls
120 lines (82 loc) · 2.56 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""
# Before code
INVALID_PASSWORDS = (
'password',
'abc123',
'123abc',
)
def validate_password(username, password):
return password != username and password not in INVALID_PASSWORDS
def create_account(username, password):
return (username, password)
def main(username, password):
valid = validate_password(username, password)
if valid:
account = create_account(username, password)
else:
print("Oh no!")
if __name__ == '__main__':
main('jim', 'jam')
main('admin', 'password') # Oh no!
main('guest', 'guest') # Oh no!
"""
# The after code
INVALID_PASSWORDS = (
'password',
'abc123',
'123abc',
)
# define a new exception subclass
class InvalidPasswordError(ValueError):
pass
# this function produces an InvalidPasswordError if the password is invalid
def validate_password(username, password):
if password == username:
raise InvalidPasswordError("username and password must be different!")
if password in INVALID_PASSWORDS:
raise InvalidPasswordError(
"This password is in a list of most commonly used passwords. Select a new one.")
def create_account(username, password):
return (username, password)
# Main function
def main(username, password):
try:
validate_password(username, password)
except InvalidPasswordError as err:
print(err)
else:
account = create_account(username, password)
finally:
print("Password validated against username and collection.")
if __name__ == '__main__':
main('jim', 'jam')
main('admin', 'password') # Oh no!
main('guest', 'guest') # Oh no!
"""
# Class Solution
class InvalidPasswordError(ValueError):
pass
INVALID_PASSWORDS = (
'password',
'abc123',
'123abc',
)
def validate_password(username, password):
if password == username:
raise InvalidPasswordError(
"Password cannot be the same as your username.")
if password in INVALID_PASSWORDS:
raise InvalidPasswordError(
"Password cannot one of the most common passwords.")
def create_account(username, password):
return (username, password)
def main(username, password):
try:
validate_password(username, password)
except InvalidPasswordError as err:
print(err)
else:
account = create_account(username, password)
finally:
print("Validated password against username and collection")
"""