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

جواب «The Honest Shop» چالش 6 از جلسه‌ی 25

سؤال

(سخت‌تر) route POST /buy فروشگاه بازی به کلاینت اعتماد می‌کند: قیمت را از بدنه برمی‌دارد و با درخواست دوم خراب می‌شود. بدنه‌ی تابع را از نو بنویس تا سرور خودش حساب کند. این چک‌ها به همین ترتیب:
1. اگر item در PRICES نبود: 404 و {"error": "no such item"}.
2. اگر count عدد صحیح (int) نبود یا کمتر از ۱ یا بیشتر از ۱۰ بود: 400 و {"error": "count must be 1 to 10"}.
3. total قیمت از PRICES ضرب در count است. اگر از wallet["coins"] بیشتر بود: 400 و {"error": "not enough coins"}.
4. وگرنه سکه‌ها کم شود و جواب {"item": ..., "count": ..., "total": ..., "coins_left": ...} با کد 200 باشد.
هر price یا total که کلاینت فرستاده نادیده گرفته شود. فراخوانی‌های ask را عوض نکن. جواب اولی {"item": "sword", "count": 2, "total": 60, "coins_left": 40} است و آخری coins_left برابر 0 دارد.

راهنما

item = data.get("item") و count = data.get("count"). if item not in PRICES: abort(404, ...)؛ if not isinstance(count, int) or count < 1 or count > 10: abort(400, ...)؛ total = PRICES[item] * count. data["price"] دیگر هیچ‌جا نیاید.

یک جواب درست

from server import app, ask, request, abort

PRICES = {"sword": 30, "shield": 50, "potion": 5}
wallet = {"coins": 100}


@app.post("/buy")
def buy():
    data = request.json or {}
    item = data.get("item")
    count = data.get("count")
    if item not in PRICES:
        abort(404, "no such item")
    if not isinstance(count, int) or count < 1 or count > 10:
        abort(400, "count must be 1 to 10")
    total = PRICES[item] * count
    if total > wallet["coins"]:
        abort(400, "not enough coins")
    wallet["coins"] = wallet["coins"] - total
    return {"item": item, "count": count, "total": total, "coins_left": wallet["coins"]}


ask("POST /buy", {"item": "sword", "count": 2, "price": 1})
ask("POST /buy", {"item": "shield", "count": 1, "total": 0})
ask("POST /buy", {"item": "potion", "count": -3})
ask("POST /buy", {"item": "dragon", "count": 1})
ask("POST /buy", {"item": "potion", "count": 8})

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