bagustyo commited on
Commit
2df1afe
·
verified ·
1 Parent(s): 302aaa6

Update main.py

Browse files

add auto Increment on parameter ID

Files changed (1) hide show
  1. main.py +13 -15
main.py CHANGED
@@ -36,6 +36,12 @@ def write_books_file(books: List[dict]):
36
  with open(DB_FILE, "w") as f:
37
  json.dump(books, f, indent=4)
38
 
 
 
 
 
 
 
39
  # ---------------------------
40
  # JSON API Endpoints
41
  # ---------------------------
@@ -53,11 +59,7 @@ def create_book_api(book: Book):
53
  Create a new book record via JSON API.
54
  """
55
  books = read_books_file()
56
-
57
- # Check if a book with the same id already exists
58
- if any(existing_book["id"] == book.id for existing_book in books):
59
- raise HTTPException(status_code=400, detail="Book with this id already exists.")
60
-
61
  books.append(book.dict())
62
  write_books_file(books)
63
  return book
@@ -101,7 +103,6 @@ def add_book_page(request: Request):
101
  @app.post("/add")
102
  def add_book(
103
  request: Request,
104
- id: int = Form(...),
105
  book_name: str = Form(...),
106
  year: int = Form(...),
107
  the_author: str = Form(...)
@@ -110,15 +111,12 @@ def add_book(
110
  Process the form data and add a new book.
111
  """
112
  books = read_books_file()
113
-
114
- # Check if a book with the same id already exists
115
- if any(existing_book["id"] == id for existing_book in books):
116
- return templates.TemplateResponse(
117
- "add_book.html",
118
- {"request": request, "error": "Book with this id already exists."}
119
- )
120
-
121
- new_book = {"id": id, "book_name": book_name, "year": year, "the_author": the_author}
122
  books.append(new_book)
123
  write_books_file(books)
124
 
 
36
  with open(DB_FILE, "w") as f:
37
  json.dump(books, f, indent=4)
38
 
39
+ def get_next_id(books: List[dict]) -> int:
40
+ """Generate the next ID for a new book."""
41
+ if books:
42
+ return max(book["id"] for book in books) + 1
43
+ return 1
44
+
45
  # ---------------------------
46
  # JSON API Endpoints
47
  # ---------------------------
 
59
  Create a new book record via JSON API.
60
  """
61
  books = read_books_file()
62
+ book.id = get_next_id(books)
 
 
 
 
63
  books.append(book.dict())
64
  write_books_file(books)
65
  return book
 
103
  @app.post("/add")
104
  def add_book(
105
  request: Request,
 
106
  book_name: str = Form(...),
107
  year: int = Form(...),
108
  the_author: str = Form(...)
 
111
  Process the form data and add a new book.
112
  """
113
  books = read_books_file()
114
+ new_book = {
115
+ "id": get_next_id(books),
116
+ "book_name": book_name,
117
+ "year": year,
118
+ "the_author": the_author
119
+ }
 
 
 
120
  books.append(new_book)
121
  write_books_file(books)
122