-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathdb.py
More file actions
58 lines (47 loc) · 1.61 KB
/
db.py
File metadata and controls
58 lines (47 loc) · 1.61 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
import sqlite3
class SQLite():
def __init__(self, file='application.db'):
self.file=file
def __enter__(self):
self.conn = sqlite3.connect(self.file)
return self.conn.cursor()
def __exit__(self, type, value, traceback):
print("Closing the connection")
self.conn.close()
class NotFoundError(Exception):
pass
class NotAuthorizedError(Exception):
pass
def blog_lst_to_json(item):
return {
'id': item[0],
'published': item[1],
'title': item[2],
'content': item[3],
'public': bool(item[4])
}
def fetch_blogs():
try:
with SQLite('application.db') as cur:
# execute the query
cur.execute('SELECT * FROM blogs where public=1')
# fetch the data and turn into a dict
return list(map(blog_lst_to_json, cur.fetchall()))
except Exception as e:
print(e)
return []
def fetch_blog(id: str):
try:
with SQLite('application.db') as cur:
# execute the query and fetch the data
cur.execute(f"SELECT * FROM blogs where id=?", [id])
result = cur.fetchone()
# return the result or raise an error
if result is None:
raise NotFoundError(f'Unable to find blog with id {id}.')
data = blog_lst_to_json(result)
if not data['public']:
raise NotAuthorizedError(f'You are not allowed to access blog with id {id}.')
return data
except sqlite3.OperationalError:
raise NotFoundError(f'Unable to find blog with id {id}.')