-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
85 lines (72 loc) · 2.8 KB
/
app.py
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
from flask import Flask, jsonify, request, Response
from BookModel import *
from settings import *
import json
@app.route('/books')
def get_books():
return jsonify({'books': Book.get_all_books()})
@app.route('/books/<int:isbn>')
def get_book_by_isbn(isbn):
return_value = Book.get_book(isbn)
return jsonify(return_value)
@app.route('/books', methods=['POST'])
def add_book():
request_data = request.get_json()
if(validBookObject(request_data)):
Book.add_book(request_data['name'], request_data['price'], request_data['isbn'])
books.insert(0, new_book)
reponse = Response("", 201, mimetype='application/json')
reponse.headers['Location'] = "/books/" + str(request_data['isbn'])
return reponse
else:
invalidBookObjecterrorMsg = {
"error": "Invalid book passed in request",
"helpString": "Check the params passed and try again"
}
response = Response(json.dumps(invalidBookObjecterrorMsg), status=400, mimetype='application/json')
return response
@app.route('/books/<int:isbn>', methods=['PUT'])
def replace_book(isbn):
request_data = request.get_json()
if(not validPutBookObject(request_data)):
invalidBookObjecterrorMsg = {
"error": "Valid book object must be passed to the request",
"helpString": "Check the params passed and try again"
}
response = Response(json.dumps(invalidBookObjecterrorMsg), status=400, mimetype='application/json')
return response
Book.replace_book(isbn, request_data['name'], request_data['price'])
response = Response("", status=204)
return response
@app.route('/books/<int:isbn>', methods=['PATCH'])
def update_book(isbn):
request_data = request.get_json()
updated_book = {}
if ("name" in request_data):
Book.update_book_name(isbn, request_data['name'])
if ("price" in request_data):
Book.update_book_price(isbn, request_data['price'])
response = Response("", status=204)
response.headers['Location'] = "/books/" + str(isbn)
return response
@app.route('/books/<int:isbn>', methods=['DELETE'])
def delete_book(isbn):
if (Book.delete_book(isbn)):
response = Response("", status=204)
return response
invalidBookObjecterrorMsg = {
"error": "Book with the ISBN number that was provided was not found."
}
response = Response(json.dumps(invalidBookObjecterrorMsg), status=404, mimetype="application/json")
return response
def validBookObject(bookObject):
if ("name" in bookObject and "price" in bookObject and "isbn" in bookObject):
return True
else:
return False
def validPutBookObject(bookObject):
if("name" in bookObject and "price" in bookObject):
return True
else:
return False
app.run(port=5000)