مثال مدیریت خطا با try (بکاند با پایتون): try: — سرور کوییز، بخش ۱
مثال 7 از درس جلسهی 31 آموزش بکاند و ساخت API با پایتون برای نوجوانان: سرور کوییز، بخش ۱
🧪 سرور کوییز را تست کن. همان روش جلسهی ۳۰: یک تابع برای هر کار و یک حلقه که میشمارد. مهمترین تست این سرور این است: «در جواب GET /api/v1/questions هیچ سؤالی کلید answer ندارد». "answer" not in q یعنی «این دیکشنری کلید answer ندارد». اگر روزی کسی SELECT * بنویسد، این تست فوراً FAIL میشود، پیش از آنکه بچهها جوابها را ببینند.
from server import app, ask, request, abort, db
db.script("""
CREATE TABLE questions (id INTEGER PRIMARY KEY, text TEXT, c1 TEXT, c2 TEXT, c3 TEXT, answer INTEGER);
INSERT INTO questions (text, c1, c2, c3, answer) VALUES
('Which code means Not Found?', '200', '404', '500', 2),
('Which method makes a new thing?', 'POST', 'GET', 'DELETE', 1),
('What do APIs usually send?', 'Photos', 'Python', 'JSON', 3);
""")
def public(q):
return {"id": q["id"], "text": q["text"], "choices": [q["c1"], q["c2"], q["c3"]]}
@app.get("/api/v1/questions")
def all_questions():
rows = db.all("SELECT id, text, c1, c2, c3 FROM questions ORDER BY id")
result = []
for q in rows:
result.append(public(q))
return result
@app.post("/api/v1/answer")
def answer():
data = request.json or {}
qid = data.get("id")
choice = data.get("choice")
if not isinstance(qid, int) or not isinstance(choice, int):
abort(400, "send id and choice as numbers")
if choice not in (1, 2, 3):
abort(400, "choice must be 1, 2 or 3")
q = db.one("SELECT answer FROM questions WHERE id = ?", qid)
if q is None:
abort(404, "no such question")
return {"id": qid, "correct": choice == q["answer"]}
def test_no_answers():
for q in ask("GET /api/v1/questions", quiet=True).json:
assert "answer" not in q, "the answers leak"
def test_right_answer():
r = ask("POST /api/v1/answer", {"id": 2, "choice": 1}, quiet=True)
assert r.json["correct"] is True, "choice 1 is right for question 2"
def test_bad_choice():
r = ask("POST /api/v1/answer", {"id": 2, "choice": 5}, quiet=True)
assert r.status == 400, "choice 5 should give 400"
tests = [test_no_answers, test_right_answer, test_bad_choice]
passed = 0
for test in tests:
try:
test()
print("PASS", test.__name__)
passed += 1
except AssertionError as err:
print("FAIL", test.__name__, "-", err)
print(passed, "of", len(tests), "tests passed")
این کد را همینجا در ویرایشگر پایتون اجرا کن، عددها و متنهایش را عوض کن و دوباره اجرا کن تا ببینی چه تغییری میکند.
بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال
← مثال قبلی · برگشت به درس جلسهی 31: سرور کوییز، بخش ۱ · چالشهای این جلسه