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

جواب «Step 1: Add and List» چالش 4 از جلسه‌ی 16

سؤال

قدم ۱: سه بخش خالی را کامل کن.
- check_title(title): اگر title متن نبود "title must be text"، اگر طولش کمتر از ۱ یا بیشتر از ۳۰ بود "title must be 1 to 30 characters"، وگرنه None برگرداند.
- GET /tasks: {"count": ..., "items": ...}.
- POST /tasks: اگر بدنه dict نبود 400 با send a JSON object؛ بعد check_title(data.get("title")) و اگر پیامی برگشت 400 با همان پیام؛ وگرنه کار {"id": ..., "title": ..., "done": false} با id از counter، اضافه به لیست و 201.
خط‌های ask در کد هست. دو کار اول id ۱ و ۲ می‌گیرند، سه درخواست بعدی 400، و GET آخر count برابر ۲ نشان می‌دهد.

راهنما

check_title همان کارت ۸ است با ۳۰ به‌جای عدد دیگر. در POST: task = {"id": counter["next"], "title": data["title"], "done": False} و counter["next"] = counter["next"] + 1.

یک جواب درست

from server import app, ask, request, abort

tasks = []
counter = {"next": 1}

def check_title(title):
    if not isinstance(title, str):
        return "title must be text"
    if len(title) < 1 or len(title) > 30:
        return "title must be 1 to 30 characters"
    return None

@app.get("/tasks")
def all_tasks():
    return {"count": len(tasks), "items": tasks}

@app.post("/tasks")
def add_task():
    data = request.json
    if not isinstance(data, dict):
        abort(400, "send a JSON object")
    problem = check_title(data.get("title"))
    if problem is not None:
        abort(400, problem)
    task = {"id": counter["next"], "title": data["title"], "done": False}
    counter["next"] = counter["next"] + 1
    tasks.append(task)
    return task, 201

ask("POST /tasks", {"title": "Math homework"})
ask("POST /tasks", {"title": "Feed the cat"})
ask("POST /tasks", {"title": ""})
ask("POST /tasks", {"title": 42})
ask("POST /tasks")
ask("GET /tasks")

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