بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 1: Saving Scores» چالش 4 از جلسه‌ی 20

سؤال

قدم ۱: مسیر POST /scores را کامل کن. سه بررسی، به همین ترتیب، و هر مشکل یک متن در لیست problems:
- player متن غیرخالی نیست → player is required
- game در GAMES نیست → game must be Snake or Pong
- points عدد صحیح از ۰ تا ۱۰۰۰ نیست → points must be a whole number from 0 to 1000

اگر مشکلی بود 400 با {"errors": [...]} (این بخش آماده است). وگرنه با INSERT و ? ذخیره کن و ردیف تازه را با 201 برگردان. خروجی:
``
POST /scores → 201 Created
{"id": 9, "player": "Leila", "game": "Pong", "points": 45}
POST /scores → 400 Bad Request
{"errors": ["player is required", "game must be Snake or Pong", "points must be a whole number from 0 to 1000"]}
POST /scores → 400 Bad Request
{"errors": ["points must be a whole number from 0 to 1000"]}
``

راهنما

مثلاً if not isinstance(points, int) or points < 0 or points > 1000: problems.append(...). آخر: done = db.run("INSERT INTO scores (player, game, points) VALUES (?, ?, ?)", (player, game, points)) و return db.one("SELECT * FROM scores WHERE id = ?", (done.id,)), 201.

یک جواب درست

from server import app, ask, db, request, abort

db.script('''
CREATE TABLE scores (id INTEGER PRIMARY KEY, player TEXT, game TEXT, points INTEGER);
INSERT INTO scores (player, game, points) VALUES ('Sara', 'Snake', 145), ('Ali', 'Snake', 95), ('Mina', 'Snake', 140);
INSERT INTO scores (player, game, points) VALUES ('Sara', 'Pong', 30), ('Reza', 'Pong', 160), ('Kian', 'Snake', 140);
INSERT INTO scores (player, game, points) VALUES ('Sara', 'Snake', 150), ('Omid', 'Pong', 38);
''')

GAMES = ["Snake", "Pong"]

@app.post("/scores")
def add_score():
    data = request.json or {}
    player = data.get("player")
    game = data.get("game")
    points = data.get("points")
    problems = []
    if not isinstance(player, str) or player == "":
        problems.append("player is required")
    if game not in GAMES:
        problems.append("game must be Snake or Pong")
    if not isinstance(points, int) or points < 0 or points > 1000:
        problems.append("points must be a whole number from 0 to 1000")
    if problems:
        return {"errors": problems}, 400
    done = db.run("INSERT INTO scores (player, game, points) VALUES (?, ?, ?)", (player, game, points))
    return db.one("SELECT * FROM scores WHERE id = ?", (done.id,)), 201

ask("POST /scores", {"player": "Leila", "game": "Pong", "points": 45})
ask("POST /scores", {"player": "", "game": "Chess", "points": 5000})
ask("POST /scores", {"player": "Nima", "game": "Snake", "points": "lots"})

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن