-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
58 lines (51 loc) · 1.48 KB
/
model.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
import json
from datetime import datetime
GUESTBOOK_ENTRIES_FILE = "entries.json"
entries = []
next_id = 0
def init():
global entries
global next_id
try:
f = open(GUESTBOOK_ENTRIES_FILE)
entries = json.loads(f.read())
f.close()
except:
entries = []
for each_dict in entries:
if each_dict['id'] >= next_id:
next_id = each_dict['id'] + 1
def get_entries():
global entries
return entries
def add_entry(name, text):
global entries, GUESTBOOK_ENTRIES_FILE, next_id
now = datetime.now()
time_string = now.strftime("%b %d, %Y %-I:%M %p")
# if you have an error using this format, just use
# time_string = str(now)
entry = {"author": name, "text": text, "timestamp": time_string, "id": next_id}
next_id += 1
entries.insert(0, entry) ## add to front of list
try:
f = open(GUESTBOOK_ENTRIES_FILE, "w")
dump_string = json.dumps(entries)
f.write(dump_string)
f.close()
except:
print("ERROR! Could not write entries to file.")
def delete_entry(__id):
global entries
for index in range(len(entries)):
each_dict = entries[index]
if each_dict['id'] == int(__id):
entries.pop(index)
break
# for loop
try:
f = open(GUESTBOOK_ENTRIES_FILE, "w")
dump_string = json.dumps(entries)
f.write(dump_string)
f.close()
except:
print("ERROR! Could not write entries to file.")