جواب «No Book Twice» چالش 6 از جلسهی 18
سؤال
(سختتر) مسیر POST /books را بساز. بدنه title و year دارد. به این ترتیب بررسی کن:
1. اگر year عدد صحیح نیست (isinstance(..., int))، 400 با {"error": "year must be a whole number"}.
2. اگر کتابی با همین title از قبل هست (با db.one و ?)، 409 با {"error": "this book is already here"}.
3. وگرنه INSERT و 201 با ردیف تازه.
مسیر GET /books آماده است. خروجی:
````
POST /books → 201 Created
{"id": 3, "title": "Wonder", "year": 2012}
POST /books → 409 Conflict
{"error": "this book is already here"}
POST /books → 400 Bad Request
{"error": "year must be a whole number"}
GET /books → 200 OK
[
{"id": 1, "title": "The Hobbit", "year": 1937},
{"id": 2, "title": "Coraline", "year": 2002},
{"id": 3, "title": "Wonder", "year": 2012}
]
راهنما
if not isinstance(data.get("year"), int): abort(400, ...). بعد if db.one("SELECT id FROM books WHERE title = ?", (data["title"],)) is not None: abort(409, ...). آخر INSERT و return db.one(...), 201.
یک جواب درست
from server import app, ask, db, request, abort
db.script('''
CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, year INTEGER);
INSERT INTO books (title, year) VALUES ('The Hobbit', 1937);
INSERT INTO books (title, year) VALUES ('Coraline', 2002);
''')
@app.get("/books")
def all_books():
return db.all("SELECT * FROM books ORDER BY id")
@app.post("/books")
def add_book():
data = request.json or {}
if not isinstance(data.get("year"), int):
abort(400, "year must be a whole number")
if db.one("SELECT id FROM books WHERE title = ?", (data.get("title"),)) is not None:
abort(409, "this book is already here")
done = db.run("INSERT INTO books (title, year) VALUES (?, ?)", (data.get("title"), data["year"]))
return db.one("SELECT * FROM books WHERE id = ?", (done.id,)), 201
ask("POST /books", {"title": "Wonder", "year": 2012})
ask("POST /books", {"title": "The Hobbit", "year": 1937})
ask("POST /books", {"title": "Matilda", "year": "1988"})
ask("GET /books")
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن