-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
63 lines (43 loc) · 1.58 KB
/
Copy pathapp.py
File metadata and controls
63 lines (43 loc) · 1.58 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
from flask import Flask, request, jsonify
from flask_migrate import Migrate
from db import db
from models.book import Book
app = Flask(__name__)
#@app.route('/hello')
#def hello():
# return 'Hello World!'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:password@localhost:5432/selfdb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
migrate = Migrate(app, db)
@app.route('/books', methods=['POST'])
def add_book():
data = request.get_json()
new_book = Book(title=data['title'], author=data['author'], description=data['description'])
db.session.add(new_book)
db.session.commit()
return jsonify({'book': new_book.title}), 201
@app.route('/books', methods=['GET'])
def get_all():
books = Book.query.all()
return jsonify([book.as_dict() for book in books])
@app.route('/books/<uuid:book_id>', methods=['GET'])
def get_book(book_id):
book = Book.query.get_or_404(book_id)
return jsonify(book.as_dict())
@app.route('/books/<uuid:book_id>', methods=['PATCH'])
def update_book(book_id):
book = Book.query.get_or_404(book_id)
data = request.get_json()
for key, value in data.items():
setattr(book, key, value)
db.session.commit()
return jsonify({'message': 'Book successfully updated.'})
@app.route('/books/<uuid:book_id>', methods=['DELETE'])
def delete(book_id):
book = Book.query.get_or_404(book_id)
db.session.delete(book)
db.session.commit()
return jsonify({'message': 'Book successfully removed.'})
if __name__ == '__main__':
app.run(debug=True, port=5000, host='0.0.0.0')