جواب «Check One Answer» چالش 5 از جلسهی 31
سؤال
(سختتر) مسیر POST /api/v1/answer را کامل کن. بدنه مثل {"id": 1, "choice": 2} است. به همین ترتیب بررسی کن:
1. اگر id یا choice عدد صحیح (int) نیست: 400 با {"error": "send id and choice as numbers"}.
2. اگر choice یکی از ۱، ۲، ۳ نیست: 400 با {"error": "choice must be 1, 2 or 3"}.
3. اگر سؤال نیست: 404 با {"error": "no such question"}.
4. وگرنه 200 با {"id": ..., "correct": true} یا false. جواب درست را نفرست.
پنج ask در کد هست.
راهنما
if not isinstance(qid, int) or not isinstance(choice, int): abort(400, ...)، بعد if choice not in (1, 2, 3): abort(400, ...). q = db.one("SELECT answer FROM questions WHERE id = ?", qid) و اگر None بود 404. آخر: return {"id": qid, "correct": choice == q["answer"]}.
یک جواب درست
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);
""")
@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"]}
ask("POST /api/v1/answer", {"id": 1, "choice": 2})
ask("POST /api/v1/answer", {"id": 2, "choice": 3})
ask("POST /api/v1/answer", {"id": 2, "choice": "1"})
ask("POST /api/v1/answer", {"id": 2, "choice": 7})
ask("POST /api/v1/answer", {"id": 9, "choice": 1})
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن