Step 3: The Leaderboard چالش 6 از جلسهی 32، سخت
(سختتر) قدم ۳: کد قدم ۲ را ادامه بده. بالای درخواستها اضافه کن:
1. مسیر عمومی GET /api/v1/leaderboard (بدون توکن) که سه نفر اول را با یک سؤال SQL روی answers برگرداند: [{"name": ..., "score": ...}, ...]، score مجموع جوابهای درست، از بیشترین؛ اگر برابر بودند، به ترتیب الفبای اسم؛ LIMIT 3. (راهنما: user AS name.)
2. یک @app.after که به همهی جوابها هدر X-Version با مقدار "1" بزند.
بعد آخر برنامه این کد کلاینت را اضافه کن که سه بازیکن دیگر را ثبتنام میکند و جواب میدهد:
``python`
def play(name, password, answers):
ask("POST /api/v1/signup", {"name": name, "password": password}, quiet=True)
t = ask("POST /api/v1/login", {"name": name, "password": password}, quiet=True).json["token"]
for qid, choice in answers:
ask("POST /api/v1/answer", {"id": qid, "choice": choice}, headers={"Authorization": "Bearer " + t}, quiet=True)
play("Ali", "dog456", [(1, 2), (2, 1), (3, 3)])
play("Mina", "fish789", [(1, 2), (2, 2)])
play("Reza", "sun321", [(3, 1)])
board = ask("GET /api/v1/leaderboard")
print("X-Version:", board.headers.get("X-Version"))Ali
آخر خروجی: جدول امتیاز با ۳، Mina ۱ و Sara ۱ (هر کدام در یک خط)، و X-Version: 1`. رضا با ۰ امتیاز به سه نفر اول نمیرسد.
from server import app, ask, request, abort, db, hash_password, check_password, new_token
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);
CREATE TABLE users (name TEXT PRIMARY KEY, hash TEXT);
""")
tokens = {}
@app.post("/api/v1/signup")
def signup():
data = request.json or {}
name = data.get("name")
password = data.get("password")
if not name or not password:
abort(400, "name and password are required")
if db.one("SELECT name FROM users WHERE name = ?", name):
abort(409, "this name is taken")
db.run("INSERT INTO users (name, hash) VALUES (?, ?)", (name, hash_password(password)))
return {"name": name}, 201
@app.post("/api/v1/login")
def login():
data = request.json or {}
user = db.one("SELECT name, hash FROM users WHERE name = ?", data.get("name", ""))
if user is None or not check_password(data.get("password", ""), user["hash"]):
abort(401, "wrong name or password")
token = new_token()
tokens[token] = user["name"]
return {"token": token}
db.run("CREATE TABLE answers (user TEXT, qid INTEGER, correct INTEGER)")
@app.before
def guard():
if request.path == "/api/v1/answer":
if request.token not in tokens:
return {"error": "log in first"}, 401
request.user = tokens[request.token]
@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")
q = db.one("SELECT answer FROM questions WHERE id = ?", qid)
if q is None:
abort(404, "no such question")
if db.one("SELECT qid FROM answers WHERE user = ? AND qid = ?", (request.user, qid)):
abort(409, "you already answered this question")
correct = choice == q["answer"]
db.run("INSERT INTO answers (user, qid, correct) VALUES (?, ?, ?)", (request.user, qid, int(correct)))
score = db.value("SELECT SUM(correct) FROM answers WHERE user = ?", request.user)
return {"correct": correct, "score": score}
ask("POST /api/v1/signup", {"name": "Sara", "password": "cat123"})
ask("POST /api/v1/signup", {"name": "Sara", "password": "dog456"})
ask("POST /api/v1/signup", {"name": "Ali"})
ask("POST /api/v1/login", {"name": "Sara", "password": "nope"})
r = ask("POST /api/v1/login", {"name": "Sara", "password": "cat123"}, quiet=True)
print(r.status, len(r.json["token"]))
sara = {"Authorization": "Bearer " + r.json["token"]}
ask("POST /api/v1/answer", {"id": 1, "choice": 2})
ask("POST /api/v1/answer", {"id": 1, "choice": 2}, headers={"Authorization": "Bearer fake"})
ask("POST /api/v1/answer", {"id": 1, "choice": 2}, headers=sara)
ask("POST /api/v1/answer", {"id": 2, "choice": 3}, headers=sara)
ask("POST /api/v1/answer", {"id": 1, "choice": 1}, headers=sara)
ask("POST /api/v1/answer", {"id": 9, "choice": 1}, headers=sara)
راهنما و جواب این چالش · برگشت به درس جلسهی 32: پروژهی پایانی: سرور کوییز آنلاین میشود
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال