-
Notifications
You must be signed in to change notification settings - Fork 9
/
appMVCv2.py
273 lines (207 loc) · 6.54 KB
/
appMVCv2.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# ===========================
# Example of MVC pattern on pure Python. Whiten for "Use Python in the Web"
# course. Institute Mathematics and Computer Science at Ural Federal University
# in 2014.
#
# By Pahaz Blinov.
# ===========================
__author__ = "pahaz"
DB_FILE = "main.db"
DEBUG = False
# ===========================
#
# Utilities
#
# ===========================
from cgi import escape
from urlparse import parse_qs
import shelve
def http_status(code):
"""
Return a str representation of HTTP response status from int `code`.
"""
return "200 OK" if code == 200 else "404 Not Found"
def parse_http_post_data(environ):
"""
Parse a HTTP post data form WSGI `environ` argument.
"""
try:
request_body_size = int(environ.get("CONTENT_LENGTH", 0))
except ValueError:
request_body_size = 0
request_body = environ["wsgi.input"].read(request_body_size)
body_query_dict = parse_qs(request_body)
return body_query_dict
def parse_http_get_data(environ):
return parse_qs(environ["QUERY_STRING"])
def take_one_or_None(dict_, key):
"""
Take one value by key from dict or return None.
>>> d = {"foo":[1,2,3], "baz":7}
>>> take_one_or_None(d, "foo")
1
>>> take_one_or_None(d, "bar") is None
True
>>> take_one_or_None(d, "baz")
7
"""
val = dict_.get(key)
if type(val) in (list, tuple) and len(val) > 0:
val = val[0]
return val
# ===========================
#
# 1. Model
#
# ===========================
class TextModel(object):
def __init__(self, title, content):
self.title = title
self.content = content
class TextManager(object):
def __init__(self):
self._db = shelve.open(DB_FILE)
def get_by_title(self, title):
"""
Get Text object by name if exist else return None.
"""
content = self._db.get(title)
return TextModel(title, content) if content else None
def get_all(self):
"""
Get list of all Text objects.
"""
return [
TextModel(title, content) for title, content in self._db.items()
]
def create(self, title, content):
if title in self._db:
return False
self._db[title] = content
self._db.sync()
return True
def delete(self, title):
if title not in self._db:
return False
del self._db[title]
self._db.sync()
return True
# ===========================
#
# Controller and Router
#
# ===========================
class Router(object):
"""
Router for requests.
"""
def __init__(self):
self._paths = {}
def route(self, request_path, request_get_data):
if request_path in self._paths:
res = self._paths[request_path](request_get_data)
else:
res = self.default_response(request_get_data)
return res
def register(self, path, callback):
self._paths[path] = callback
def default_response(self, *args):
return 404, "Nooo 404!"
class TextController(object):
def __init__(self, index_view, add_view, manager):
self.index_view = index_view
self.add_view = add_view
self.model_manager = manager
def index(self, request_get_data):
title = take_one_or_None(request_get_data, "title")
current_text = self.model_manager.get_by_title(title)
all_texts = self.model_manager.get_all()
context = {
"all": all_texts,
"current": current_text,
}
return 200, self.index_view.render(context)
def add(self, request_get_data):
title = take_one_or_None(request_get_data, 'title')
content = take_one_or_None(request_get_data, 'content')
if not title or not content:
error = "Need fill the form fields."
else:
error = None
is_created = self.model_manager.create(title, content)
if not is_created:
error = "Title already exist."
context = {
'title': title,
'content': content,
'error': error,
}
return 200, self.add_view.render(context)
# ===========================
#
# View
#
# ===========================
class TextIndexView(object):
@staticmethod
def render(context):
context["titles"] = "\n".join([
"<li>{text.title}</li>".format(text=text) for text in context["all"]
])
if context["current"]:
context["content"] = """
<h1>{current.title}</h1>
{current.content}
""".format(current=context["current"])
else:
context["content"] = 'What do you want read?'
t = """
<form method="GET">
<input type=text name=title placeholder="Text title" />
<input type=submit value=read />
</form>
<form method="GET" action="/text/add">
<input type=text name=title placeholder="Text title" /> <br>
<textarea name=content placeholder="Text content!" ></textarea> <br>
<input type=submit value=write/rewrite />
</form>
<div>{content}</div>
<ul>{titles}</ul>
"""
return t.format(**context)
class RedirectView(object):
@staticmethod
def render(context):
return '<meta http-equiv="refresh" content="0; url=/text" />'
# ===========================
#
# Main
#
# ===========================
text_manager = TextManager()
controller = TextController(TextIndexView, RedirectView, text_manager)
router = Router()
router.register("/", lambda x: (200, "Index HI!"))
router.register("/text", controller.index)
router.register("/text/add", controller.add)
# ===========================
#
# WSGI
#
# ===========================
def application(environ, start_response):
request_path = environ["PATH_INFO"]
request_get_data = parse_http_get_data(environ)
# TODO: You can add this interesting line
# print(parse_http_post_data(environ))
http_status_code, response_body = router.route(request_path, request_get_data)
if DEBUG:
response_body += "<br><br> The request ENV: {0}".format(repr(environ))
response_status = http_status(http_status_code)
response_headers = [("Content-Type", "text/html")]
start_response(response_status, response_headers)
return [response_body] # it could be any iterable.
# if run as script do tests.
if __name__ == "__main__":
import doctest
doctest.testmod()