-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
122 lines (96 loc) · 2.59 KB
/
Copy pathapp.py
File metadata and controls
122 lines (96 loc) · 2.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
"""Representational state transfer (REST) API using Flask ."""
from flask import Flask
from flask_restful import Api, Resource, reqparse
import random
import json
import db
class PopularQuotes(Resource):
"""Quotes interface."""
def _get_params(self, *reqs):
parser = reqparse.RequestParser()
for req in reqs:
parser.add_argument(req)
return parser.parse_args()
def delete(self, id_):
"""Delete an existing quote with the specified id."""
res = qdb.delete_quote(id_)
if res:
return f'Quote with id {id_} has been successfully deleted.', 200
else:
return f'Quote with id {id_} does not exist!', 404
def get(self, id_=0):
"""
Retrieve a random quote or a quote with a specified id other than 0.
"""
quotes = qdb.get_all_quotes()
if isinstance(id_, str):
if id_ == 'all':
return self.get_all(quotes)
if id_ == 'authors':
return self.get_authors()
return self.get_by_name(id_)
if not id_:
return dict(random.choice([*quotes])._asdict())
for quote in quotes:
if quote.id == id_:
return dict(quote._asdict()), 200
del quotes
return 'Quote not found', 404
def get_by_name(self, name):
quotes = [*qdb.get_all_quotes(by=name)]
if quotes:
return [*map(lambda quote: dict(quote._asdict()), quotes)], 200
return 'Author not found', 404
def get_all(self, quotes):
return [*map(
lambda quote: dict(quote._asdict()),
quotes
)], 200
def get_authors(self):
with qdb.connection:
qdb.cursor.execute(
"SELECT author FROM quotes"
)
result, = [*zip(*qdb.cursor.fetchall())]
return sorted({*result}), 200
def post(self, id_):
"""Adds/creates a new quote."""
if qdb.exists(id_):
return f"Quote with id {id_} already exists", 400
params = self._get_params('author', 'quote')
qdb.add_quote(
id=int(id_),
author=params['author'],
quote=params['quote']
)
return quote, 201
def put(self, id_):
"""Modify existing quote with specified id."""
params = self._get_params('author', 'quote')
try:
with database.connection:
database.connection.execute(
"UPDATE quotes SET author=?, quote=? WHERE id=?",
(params['author'], params['quote'], id_)
)
return quote, 200
except (db.sql.OperationalError, db.sql.IntegrityError) as error:
print(error)
self.post(id_)
return quote, 201
# connect to quotes database
qdb = db.QuotesDB('database.db')
# setup application
app = Flask(__name__)
api = Api(app)
# add resource to api
api.add_resource(
PopularQuotes,
# resource urls
'/quotes',
'/quotes/',
'/quotes/<int:id_>',
'/quotes/<string:id_>'
)
if __name__ == '__main__':
app.run(debug=True)