-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
173 lines (140 loc) · 4.41 KB
/
app.py
File metadata and controls
173 lines (140 loc) · 4.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from flask import Flask, render_template, request, jsonify
from database import init_db, get_db
app = Flask(__name__)
with app.app_context():
init_db()
VALID_STATUS = ["Available", "Issued"]
def error_response(message, status_code=400):
return jsonify({"success": False, "error": message}), status_code
def success_response(message, data=None, status_code=200):
response = {
"success": True,
"message": message
}
if data is not None:
response["data"] = data
return jsonify(response), status_code
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/books", methods=["GET"])
def get_books():
query = request.args.get("q", "").strip()
db = get_db()
if query:
books = db.execute(
"""
SELECT * FROM books
WHERE title LIKE ?
OR author LIKE ?
OR genre LIKE ?
ORDER BY created_at DESC
""",
(f"%{query}%", f"%{query}%", f"%{query}%")
).fetchall()
else:
books = db.execute(
"SELECT * FROM books ORDER BY created_at DESC"
).fetchall()
return jsonify([dict(book) for book in books])
@app.route("/api/books", methods=["POST"])
def add_book():
data = request.get_json()
if not data:
return error_response("Invalid JSON data.")
title = data.get("title", "").strip()
author = data.get("author", "").strip()
genre = data.get("genre", "").strip()
year = str(data.get("year", "")).strip()
status = data.get("status", "Available").strip()
if not title or not author:
return error_response("Title and Author are required.")
if status not in VALID_STATUS:
return error_response("Invalid status value.")
if year and not year.isdigit():
return error_response("Year must be numeric.")
db = get_db()
db.execute(
"""
INSERT INTO books (title, author, genre, year, status)
VALUES (?, ?, ?, ?, ?)
""",
(title, author, genre, year, status)
)
db.commit()
return success_response("Book added successfully!", status_code=201)
@app.route("/api/books/<int:book_id>", methods=["PUT"])
def update_book(book_id):
data = request.get_json()
if not data:
return error_response("Invalid JSON data.")
title = data.get("title", "").strip()
author = data.get("author", "").strip()
genre = data.get("genre", "").strip()
year = str(data.get("year", "")).strip()
status = data.get("status", "Available").strip()
if not title or not author:
return error_response("Title and Author are required.")
if status not in VALID_STATUS:
return error_response("Invalid status value.")
if year and not year.isdigit():
return error_response("Year must be numeric.")
db = get_db()
existing_book = db.execute(
"SELECT * FROM books WHERE id=?",
(book_id,)
).fetchone()
if not existing_book:
return error_response("Book not found.", 404)
db.execute(
"""
UPDATE books
SET title=?, author=?, genre=?, year=?, status=?
WHERE id=?
""",
(title, author, genre, year, status, book_id)
)
db.commit()
return success_response("Book updated successfully!")
@app.route("/api/books/<int:book_id>", methods=["DELETE"])
def delete_book(book_id):
db = get_db()
existing_book = db.execute(
"SELECT * FROM books WHERE id=?",
(book_id,)
).fetchone()
if not existing_book:
return error_response("Book not found.", 404)
db.execute(
"DELETE FROM books WHERE id=?",
(book_id,)
)
db.commit()
return success_response("Book deleted successfully.")
@app.route("/api/stats", methods=["GET"])
def stats():
db = get_db()
total = db.execute(
"SELECT COUNT(*) FROM books"
).fetchone()[0]
available = db.execute(
"SELECT COUNT(*) FROM books WHERE status='Available'"
).fetchone()[0]
issued = db.execute(
"SELECT COUNT(*) FROM books WHERE status='Issued'"
).fetchone()[0]
genres = db.execute(
"""
SELECT COUNT(DISTINCT genre)
FROM books
WHERE genre != ''
"""
).fetchone()[0]
return jsonify({
"total": total,
"available": available,
"issued": issued,
"genres": genres
})
if __name__ == "__main__":
app.run(debug=True)