forked from Jasmit7/flask-crud
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathapp.py
81 lines (71 loc) · 2.24 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
# app.py
from flask import Flask, jsonify, request
import sqlite3
app = Flask(__name__)
@app.route('/')
def index_page():
return '<h1>Welcome to Flask Books App</h1>'
@app.route('/books', methods=['GET'])
def get_books():
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute('SELECT * FROM books')
rows = cur.fetchall()
books = []
for row in rows:
book = {
'id': row[0],
'title': row[1],
'author': row[2],
'published': row[3]
}
books.append(book)
conn.close()
return jsonify(books)
@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute('SELECT * FROM books WHERE id=?', (book_id,))
row = cur.fetchone()
if row:
book = {
'id': row[0],
'title': row[1],
'author': row[2],
'published': row[3]
}
conn.close()
return jsonify(book)
else:
conn.close()
return jsonify({'error': 'Book not found'})
@app.route('/books', methods=['POST'])
def create_book():
book = request.get_json()
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute('INSERT INTO books (title, author, published) VALUES (?, ?, ?)', (book['title'], book['author'], book['published']))
book_id = cur.lastrowid
conn.commit()
conn.close()
return jsonify({'id': book_id, 'message': 'Book created successfully'})
@app.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
book = request.get_json()
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute('UPDATE books SET title=?, author=?, published=? WHERE id=?', (book['title'], book['author'], book['published'], book_id))
conn.commit()
conn.close()
return jsonify({'message': 'Book updated successfully'})
@app.route('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
conn = sqlite3.connect('books.db')
cur = conn.cursor()
cur.execute('DELETE FROM books WHERE id=?', (book_id,))
conn.commit()
conn.close()
return jsonify({'message': 'Book deleted successfully'})
if __name__ == '__main__':
app.run()