-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.py
129 lines (104 loc) · 4.09 KB
/
rest.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
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
from flask import Flask, request, g
from flask_restful import Resource, Api, reqparse
import sqlite3
app = Flask(__name__)
api = Api(app)
# Database initialization and connection within the Flask context
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect('library.db')
return db
# Create tables and seed database before each request
@app.before_request
def before_request():
g.db = get_db()
g.cursor = g.db.cursor()
# Close the database connection after each request
@app.teardown_request
def teardown_request(exception=None):
if hasattr(g, '_database'):
g.db.commit()
g.db.close()
def create_table():
# Connect to the SQLite database (or create it if it doesn't exist)
connection = sqlite3.connect('library.db')
cursor = connection.cursor()
# Create the 'books' table
cursor.execute('''
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
publication_year INTEGER
)
''')
# Commit the changes and close the connection
connection.commit()
connection.close()
# Helper function to seed the database with mock data
def seed_database():
# Connect to the SQLite database
connection = sqlite3.connect('library.db')
cursor = connection.cursor()
# Create the 'books' table if it doesn't exist
create_table()
# Insert data into the 'books' table
cursor.execute("INSERT INTO books (title, author, publication_year) VALUES (?, ?, ?)", ('Book 1', 'Author 1', 2000))
# Commit the changes and close the connection
connection.commit()
connection.close()
# Call the function to create the 'books' table
create_table()
# Call the function to seed the database
seed_database()
# Endpoint 1: Retrieve All Books
class AllBooks(Resource):
def get(self):
try:
g.cursor.execute("SELECT * FROM books")
books = g.cursor.fetchall()
return {'books': books}, 200
except Exception as e:
return {'error': str(e)}, 500
# Endpoint 2: Add a New Book
class AddBook(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('title', type=str, required=True, help='Title is required')
parser.add_argument('author', type=str, required=True, help='Author is required')
parser.add_argument('publication_year', type=int, required=True, help='Publication year is required')
args = parser.parse_args()
try:
g.cursor.execute("INSERT INTO books (title, author, publication_year) VALUES (?, ?, ?)",
(args['title'], args['author'], args['publication_year']))
g.db.commit()
return {'message': 'Book added successfully'}, 201
except Exception as e:
return {'error': str(e)}, 500
# Endpoint 3: Update Book Details
class UpdateBook(Resource):
def put(self, book_id):
parser = reqparse.RequestParser()
parser.add_argument('title', type=str, required=True, help='Title is required')
parser.add_argument('author', type=str, required=True, help='Author is required')
parser.add_argument('publication_year', type=int, required=True, help='Publication year is required')
args = parser.parse_args()
try:
g.cursor.execute("UPDATE books SET title=?, author=?, publication_year=? WHERE id=?",
(args['title'], args['author'], args['publication_year'], book_id))
g.db.commit()
if g.cursor.rowcount == 0:
return {'error': 'Book not found'}, 404
return {'message': 'Book updated successfully'}, 200
except Exception as e:
return {'error': str(e)}, 500
# Add resources to the API
api.add_resource(AllBooks, '/api/books')
api.add_resource(AddBook, '/api/books')
api.add_resource(UpdateBook, '/api/books/<int:book_id>')
# Seed the database with mock data
seed_database()
# Run the application
if __name__ == '__main__':
app.run(debug=True)