جواب «Step 3: Delete and No Twins» چالش 6 از جلسهی 16
سؤال
(سختتر) قدم ۳: به کد قدم ۲ اضافه کن:
- DELETE /tasks/<int:task_id>: با find_task پیدا کن (پس 404 خودش میآید)، پاک کن و "", 204.
- در POST /tasks، بعد از بررسی عنوان: اگر کاری با همین عنوان هست (حروف بزرگ و کوچک مهم نیست)، 409 با پیام there is already a task called Math homework (عنوانِ کارِ موجود).
بعد این خطها را آخر برنامه اضافه کن:
```
ask("POST /tasks", {"title": "math homework"})
ask("DELETE /tasks/1")
ask("DELETE /tasks/1")
ask("POST /tasks", {"title": "Clean my room"})
ask("GET /tasks")id
کار تازهی آخر باید ۳ بگیرد، و GET` آخر دو کار نشان دهد: ۲ و ۳.
راهنما
در POST پیش از ساختن کار: for task in tasks: و if task["title"].lower() == data["title"].lower(): abort(409, "there is already a task called " + task["title"]). DELETE: task = find_task(task_id)، tasks.remove(task)، return "", 204.
یک جواب درست
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}
def find_task(task_id):
for task in tasks:
if task["id"] == task_id:
return task
abort(404, "no task " + str(task_id))
@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)
for task in tasks:
if task["title"].lower() == data["title"].lower():
abort(409, "there is already a task called " + task["title"])
task = {"id": counter["next"], "title": data["title"], "done": False}
counter["next"] = counter["next"] + 1
tasks.append(task)
return task, 201
@app.patch("/tasks/<int:task_id>")
def change_task(task_id):
task = find_task(task_id)
data = request.json
if "title" in data and check_title(data["title"]) is not None:
abort(400, check_title(data["title"]))
if "done" in data and not isinstance(data["done"], bool):
abort(400, "done must be true or false")
if "title" in data:
task["title"] = data["title"]
if "done" in data:
task["done"] = data["done"]
return task
@app.delete("/tasks/<int:task_id>")
def delete_task(task_id):
task = find_task(task_id)
tasks.remove(task)
return "", 204
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")
ask("PATCH /tasks/1", {"done": True})
ask("PATCH /tasks/2", {"title": "Feed the dog", "done": "yes"})
ask("PATCH /tasks/2", {"title": ""})
ask("PATCH /tasks/9", {"done": True})
ask("GET /tasks")
ask("POST /tasks", {"title": "math homework"})
ask("DELETE /tasks/1")
ask("DELETE /tasks/1")
ask("POST /tasks", {"title": "Clean my room"})
ask("GET /tasks")
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن