-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
265 lines (229 loc) · 6.59 KB
/
Copy pathapp.py
File metadata and controls
265 lines (229 loc) · 6.59 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import json
import os
from pathlib import Path
from flasgger import Swagger
from flask import Flask, current_app, jsonify, request
BASE_DIR = Path(__file__).resolve().parent
DEFAULT_DATA_FILE = BASE_DIR / 'data' / 'books.json'
def default_books():
return [
{
'name': 'The Pragmatic Programmer',
'price': 299,
'isbn': 100,
'author': 'Andrew Hunt'
},
{
'name': 'Clean Code',
'price': 399,
'isbn': 101,
'author': 'Robert C. Martin'
}
]
def load_books(data_file):
path = Path(data_file)
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
initial_data = default_books()
path.write_text(json.dumps(initial_data, indent=2), encoding='utf-8')
return initial_data
with path.open('r', encoding='utf-8') as file_handle:
books = json.load(file_handle)
if not isinstance(books, list):
return default_books()
return books
def persist_books(books):
data_file = Path(current_app.config['BOOKS_DATA_FILE'])
data_file.parent.mkdir(parents=True, exist_ok=True)
with data_file.open('w', encoding='utf-8') as file_handle:
json.dump(books, file_handle, indent=2)
def valid_book_object(book_object):
return isinstance(book_object, dict) and all(
field in book_object for field in ('name', 'price', 'isbn', 'author')
)
def find_book_index(books, isbn):
for index, book in enumerate(books):
if book.get('isbn') == isbn:
return index
return -1
def create_app(test_config=None):
app = Flask(__name__)
app.config.from_mapping(
BOOKS_DATA_FILE=os.getenv('BOOKS_DATA_FILE', str(DEFAULT_DATA_FILE)),
HOST=os.getenv('HOST', '0.0.0.0'),
PORT=int(os.getenv('PORT', '5000')),
JSON_SORT_KEYS=False,
)
if test_config:
app.config.update(test_config)
books = load_books(app.config['BOOKS_DATA_FILE'])
Swagger(app, template={
'swagger': '2.0',
'info': {
'title': 'Books API',
'description': 'A small Flask API for managing books.',
'version': '1.0.0'
},
'schemes': ['http', 'https'],
})
@app.route('/books', methods=['GET'])
def get_books():
"""
Get all books
---
tags:
- Books
responses:
200:
description: A list of books
"""
return jsonify({'books': books})
@app.route('/books', methods=['POST'])
def add_book():
"""
Add a new book
---
tags:
- Books
parameters:
- in: body
name: body
required: true
schema:
type: object
required:
- name
- price
- isbn
- author
properties:
name:
type: string
price:
type: integer
isbn:
type: integer
author:
type: string
responses:
201:
description: Book created successfully
400:
description: Invalid book payload
"""
request_data = request.get_json(silent=True)
if not valid_book_object(request_data):
return jsonify({'error': 'Invalid book payload'}), 400
books.insert(0, request_data)
persist_books(books)
return jsonify(request_data), 201
@app.route('/books/<int:isbn>', methods=['GET'])
def get_book_by_isbn(isbn):
"""
Get a book by ISBN
---
tags:
- Books
parameters:
- in: path
name: isbn
type: integer
required: true
responses:
200:
description: Book item found
404:
description: Book not found
"""
index = find_book_index(books, isbn)
if index == -1:
return jsonify({'error': 'Book not found'}), 404
book = books[index]
return jsonify({
'name': book['name'],
'price': book['price'],
'isbn': book['isbn'],
'author': book['author']
})
@app.route('/books/<int:isbn>', methods=['PUT'])
def replace_book(isbn):
"""
Replace a book by ISBN
---
tags:
- Books
parameters:
- in: path
name: isbn
type: integer
required: true
- in: body
name: body
required: true
schema:
type: object
required:
- name
- price
- isbn
- author
properties:
name:
type: string
price:
type: integer
isbn:
type: integer
author:
type: string
responses:
200:
description: Book updated successfully
400:
description: Invalid book payload
404:
description: Book not found
"""
request_data = request.get_json(silent=True)
if not valid_book_object(request_data):
return jsonify({'error': 'Invalid book payload'}), 400
index = find_book_index(books, isbn)
if index == -1:
return jsonify({'error': 'Book not found'}), 404
updated_book = {
'name': request_data['name'],
'price': request_data['price'],
'author': request_data['author'],
'isbn': isbn
}
books[index] = updated_book
persist_books(books)
return jsonify(updated_book)
@app.route('/books/<int:isbn>', methods=['DELETE'])
def delete_book(isbn):
"""
Delete a book by ISBN
---
tags:
- Books
parameters:
- in: path
name: isbn
type: integer
required: true
responses:
204:
description: Book deleted successfully
404:
description: Book not found
"""
index = find_book_index(books, isbn)
if index == -1:
return jsonify({'error': 'Book not found'}), 404
books.pop(index)
persist_books(books)
return '', 204
return app
app = create_app()
if __name__ == '__main__':
app.run(host=app.config['HOST'], port=app.config['PORT'])