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 دارد.
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
total = data["price"] * data["count"]
wallet["coins"] = wallet["coins"] - total
return {"item": data["item"], "count": data["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})
راهنما و جواب این چالش · برگشت به درس جلسهی 25: هیچوقت به کلاینت اعتماد نکن
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال