-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
78 lines (62 loc) · 2.27 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
__author__ = 'ZackDev'
from abc import ABC, abstractmethod
import os
import random as random
import xml.dom.minidom as minidom
class Data:
def __init__(self, author, quote, image_path):
self.author = author
self.quote = quote
self.image_path = image_path
class AbstractModel(ABC):
xml_file = 'cites.xml'
path_to_img = 'img/'
image_type = '.png'
default_image = path_to_img + 'default' + image_type
@abstractmethod
def get_quote(self):
raise NotImplementedError
def __init__(self):
self.data_source = minidom.parse(self.xml_file)
self.quotes = []
self._populate_quotes()
def _populate_quotes(self):
# there are the following cases:
# -author tag without name -> name: unknown, file: default_image
# -author tag with name but missing image -> name: author, file: default_image
# -author tag with name and image -> name: author, file: specific_image
authors = self.data_source.getElementsByTagName('author')
for author in authors:
image_path = self.default_image
name = author.getAttribute('name')
image = author.getAttribute('image')
if name is None:
name = 'Unknown'
if image is not None:
temp_path = self.path_to_img + image
if self._file_exists(temp_path) is True:
image_path = temp_path
else:
image_path = self.default_image
quotes = author.getElementsByTagName('cite')
for quote in quotes:
quote = quote.firstChild.nodeValue
self.quotes.append(Data(name, quote, image_path))
def _file_exists(self, path_to_file):
return os.path.isfile(path_to_file)
class RandomOrderModel(AbstractModel):
def get_quote(self):
return self._get_random_quote()
def _get_random_quote(self):
if len(self.quotes) > 0:
return random.choice(self.quotes)
else:
return None
class SequentialOrderModel(AbstractModel):
def get_quote(self):
return self._pop_quote()
def _pop_quote(self):
try:
return self.quotes.pop(0)
except Exception:
return None