Lesson 74 taught you the re module and Lesson 73 taught you classes. This lab is where you put them together. You write a login checker with one username rule and five password rules, you run five test logins and watch four fail for the right reasons, and you model the checks as classes so one loop can run every kind of check. By the end you have a checker that returns every problem, not just the first, and a loop that needs no change when a third check kind arrives.
Difficulty: Intermediate · Know this first: Lesson 74 — Python for DevOps; Lab 153
Every hop charges rent in milliseconds. The bar below is a worked example for this lesson's scenario — not a measurement from a live system — but the shape is honest: on a cache hit the trip is almost free, on a miss the kitchen eats the budget. Step through the lesson or switch the scenario and watch the bar change.
Extra diagram · from scratch to master
Start with one username pattern. Add one box at a time until the loop runs three kinds of check unchanged.
The budget bar above shows three fixed stories. This simulator lets you write your own. Move a slider and watch the checking, the classes, and the total change in the budget bar, in the hop timings, and in the total. The numbers are a teaching example, not live measurements. The shape is the lesson: more logins means more checking, and an early return costs a retry per login.
How many logins the checker runs. Each login is checked against the same six rules, so more logins means a longer checking hop.
How many kinds of check the loop runs. Each kind is one more class, and the loop stays the same however many there are.
How many times a user retries because the checker named only the first problem. Each retry costs about 2 min.
Try this: (1) Set logins to 5, kinds to 2, retries to 0. The check is about 2 min, the classes about 2 min, the proof about 1 min, and the total is about 10 min. (2) Set all three to the worst end: 50 logins, 6 kinds, 5 retries. The check is about 6 min, the classes about 4 min, the proof about 11 min, and the total is about 26 min. Same checker. Only the inputs changed.
Three questions. No score is saved anywhere — this is just you against the material.
Here is the login checker from this lab, ready to edit. Change it, then run the check. The check looks for the four things a working checker needs: the username pattern, a capital rule, a digit rule, and a list that collects every problem.
Try breaking it on purpose: delete the $ from the pattern, or return after the first problem. Run the check and watch it fail. Then press Reset and try a change that keeps it passing, like adding the small-letter rule.
Expected output when it passes: The checker anchors the username pattern, checks capital and digit, and collects every problem in a list. A login with three problems reports all three.
I take the same checker four times here. First I write the pattern. Then I collect the problems. Then I model the checks. Last I prove the loop.
Flags in the next block, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
python3 login.py runs the login checker. No flags. The file name is the argument, not a flag. The output lists five logins and says OK or names the problem for each one.python3 -c "import re; print(bool(re.match(r'^[a-z][a-z0-9_]{2,15}$', 'mohan')))" tests one pattern from the command line. The -c means command string. I use it to test a regex before I put it in the script, because a wrong pattern in the script fails five logins at once.python3 -m py_compile login.py checks_oop.py checks the syntax of both files without running them. The -m means run a library module as a script. The py_compile module compiles the files and reports the first syntax error it finds. I run it with both file names at once, because a typo in either file breaks the lab.python3 --version prints the version. I run it first on a new box, because the version decides what the code can use.mkdir -p ~/lab-login && cd ~/lab-login && python3 --version makes the lab folder, moves into it, and prints the version. The -p is the parents flag. The && means run the next command only if this one worked.Check it: run python3 -c "import re; print(bool(re.match(r'^[a-z][a-z0-9_]{2,15}$', 'mohan')))" and see True. Then change mohan to Mohan and see False, because the pattern wants a small first letter.
Definition: A regular expression is a rule written in one line. ^ anchors the start, $ anchors the end, [a-z] means one small letter, {2,15} means between 2 and 15 of the thing before it. re.match checks the pattern against the start of the value.
Types:
Uses: I use a pattern when the rule is about the shape of a value: a username, an email, a code. Try it now: test mohan, Mohan, and mo against the lab pattern and check the answers are True, False, False.
Dimensions: At low volume everything is instant. What breaks first is a missing anchor: without $, 'Mohan!' matches the middle and passes.
Flags in the next block, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
python3 login.py runs the checker again. No flags. The five logins should print the same answers every time, because the rules did not change.Check it: run the script and read the five lines. mohan / Sunrise9! should be the only OK. The other four should each name their problem.
Definition: A password rule is one re.search per rule: one capital, one small letter, one digit, one special character, and a length check. Each rule is its own line, so a password can fail three at once and the checker can name all three.
Types:
Uses: I use one rule per check whenever the user needs to know what to fix. Try it now: run the login Sunrise and check it reports three reasons.
Dimensions: As the rules grow, the list grows, and the code stays the same shape. What breaks is a single pattern for all the rules: it cannot name which rule failed.
Flags in the next block, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
python3 checks_oop.py runs the class demo. No flags. The output shows two checks reporting healthy and the base check refusing to run, which is the abstraction working as designed.python3 -c "from checks_oop import Check; Check('base').run()" runs one line against the module. The -c is the command string flag. The import runs the module file, and the call raises the same error the script catches.Check it: run python3 checks_oop.py and read the last line. The base check should print its refusal, not a crash.
Definition: A class is a kind of thing with data and behaviour. Inheritance shares the base: subclasses take name and _last from Check. Encapsulation hides _last behind the status property. Abstraction is the base refusing to run, so every subclass must say how it runs.
Types:
Uses: I use classes when the same job has several kinds, and one loop must run them all. Try it now: add DiskCheck to the loop and check the loop is unchanged.
Dimensions: At ten times the kinds, the loop still works, and the classes stay small. What breaks is a subclass that reads _last straight from outside: the convention is there so the class can change how it stores the value.
Flags in the next block, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
python3 checks_oop.py runs the demo one more time. No flags. Adding a kind of check should mean adding a class, not changing the loop, and the output should stay the same shape.Check it: run the script, then add a third check class to the file and run it again. The loop should print three lines with no change to the loop itself.
Definition: At this level the design is judged by one test: add a kind, change nothing. The loop calls run() and reads status, and it never asks what kind a check is. That is polymorphism, and it is the reason the base class exists.
Types:
Uses: I use this when a system will grow kinds I cannot name today. Try it now: add a fourth kind and confirm the loop is still unchanged.
Dimensions: At a hundred kinds, the loop is the same shape, and the classes are the same size. What breaks is a loop that asks the kind: every new kind means a new branch, and the loop grows forever.
Flags in the next block, letter by letter. I read every flag out loud before I run a command I copied. A flag I cannot explain is a flag I do not run yet.
python3 login.py runs the checker. No flags. The output should list five logins with their answers.python3 checks_oop.py runs the class demo. No flags. The output should show two healthy checks and the base check refusal.python3 -m py_compile login.py checks_oop.py && echo OK checks both files and prints OK only when both pass. The -m is the module flag. The && means run the echo only if the compile worked. Silence from the compile plus the OK line is the proof both files are clean.Check it: run python3 -m py_compile login.py checks_oop.py && echo OK. The answer should be one word: OK.
The login checker, the whole file. Do this: save it as login.py and run python3 login.py. Expected output: five lines, starting mohan / Sunrise9! -> OK, and the Sunrise line names three reasons.
import re
USER_RE = re.compile(r"^[a-z][a-z0-9_]{2,15}$")
PW_RULES = [("at least 8 characters", lambda p: len(p) >= 8),
("one capital letter", lambda p: re.search(r"[A-Z]", p)),
("one small letter", lambda p: re.search(r"[a-z]", p)),
("one digit", lambda p: re.search(r"[0-9]", p)),
("one of !@#$%^&*", lambda p: re.search(r"[!@#$%^&*]", p))]
def check_login(user, pw):
problems = []
if not USER_RE.match(user):
problems.append("username must start with a small letter and be 3-16 small letters, digits, or _")
for name, rule in PW_RULES:
if not rule(pw):
problems.append("password needs " + name)
return problems
for u, p in [("mohan", "Sunrise9!"), ("Mohan", "Sunrise9!"), ("mo", "Sunrise9!"),
("mohan", "sunrise9"), ("mohan", "Sunrise")]:
probs = check_login(u, p)
print(u, "/", p, "->", "OK" if not probs else "; ".join(probs))
The five worked cases, with reasons. mohan / Sunrise9! is OK. Mohan fails the username rule. mo fails the username rule. sunrise9 needs one capital letter and one of !@#$%^&*. Sunrise needs at least 8 characters, one digit, and one of !@#$%^&*. Do this: run the script and check every line matches this list.
The classes, the whole file. Do this: save it as checks_oop.py and run python3 checks_oop.py. Expected output: web -> healthy | status: healthy, api -> healthy | status: healthy, then base check: every check must say how it runs.
class Check:
def __init__(self, name):
self.name = name; self._last = None
def run(self):
raise NotImplementedError("every check must say how it runs")
@property
def status(self):
return self._last
class HttpCheck(Check):
def run(self):
self._last = "healthy"; return self._last
class PingCheck(Check):
def run(self):
self._last = "healthy"; return self._last
for c in [HttpCheck("web"), PingCheck("api")]:
print(c.name, "->", c.run(), "| status:", c.status)
try:
Check("base").run()
except NotImplementedError as e:
print("base check:", e)
At 10x the logins, the shape holds and the checker runs the same rules. At 100x, the design changes: the rules move into a policy file, and the checker reads the file instead of hard-coding the rules. The list never changes, though. Every problem is still collected, and the whole list is still returned.
A login page told users only the first thing wrong with their password. A user with a short password that had no digit and no special character fixed the length, retried, failed on the digit, fixed the digit, retried, and failed on the special character. Three round trips for one password, and the third failure made the account lock for an hour. The checker knew all three problems on the first try. It just returned after the first one.
Two things. First, every checker in the codebase returns a list of problems, never a single string. Second, the login page prints the whole list, so the user fixes everything in one go. Try it now: run the Sunrise login and count the reasons. If it names one, the checker stops early.
Build a login checker for a new rule set you choose, plus a third check class that the existing loop runs with no change. It passes when a login with three problems reports all three, and the loop is unchanged after the new class arrives.
Success looks like this: the five worked cases print as in the lesson, the new rule is named when it fails, the one-reason login names exactly one reason, and the loop file is byte-identical except for the one line that adds DiskCheck to the list. If the loop has a new branch, the design is wrong.
If the pattern passes a bad username, an anchor is missing. If a rule never fires, the re.search pattern is wrong: [A-Z] is capital, [a-z] is small. If the base class runs instead of refusing, the raise line is missing. If the new class breaks the loop, it does not inherit from Check.