forked from ctb/meep
/
meep_example_app.py
439 lines (328 loc) · 14.6 KB
/
meep_example_app.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import meeplib
import traceback
import cgi
import meepcookie
import time
import sqlite3
import uuid
from file_server import FileServer
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
db = sqlite3.connect('foo2.db')
c = db.cursor()
def session_login(c, username):
session_cookie = str(uuid.uuid4())
username=str(username)
c.execute('INSERT INTO sessions (username, cookie) VALUES (?, ?)', (username, session_cookie))
return session_cookie
def session_get(c, session_cookie):
username = None
session_cookie=str(session_cookie)
#print "INSIDE THE FUNCTION COOKIE"+ session_cookie
c.execute('SELECT username FROM sessions WHERE cookie=?', [session_cookie])
# c.execute('SELECT * FROM sessions')
try:
username = c.fetchone()[0] #the cookie looks the same....
except:
pass
return username
def session_delete(c, session_cookie):
session_cookie=str(session_cookie)
c.execute('DELETE from sessions WHERE cookie=?', [session_cookie])
def render_page(filename, **variables):
template = env.get_template(filename)
x = template.render(**variables)
return str(x)
def initialize():
# try:
#meeplib.saveUSER('test','foo',meeplib._get_next_user_id())
#u = meeplib.User('test', 'foo',-1)
#meeplib.loadUSER()
# except:
# print "NO FILE"
# create a default user
# create a single message
# meeplib.Message('my title', 'This is my message NOW!', u,-1)
# meeplib.Message('title', 'lol', u,-1)
#meeplib.Message('my', 'test', u,-1)
# meeplib.Message('test', 'my', u,-1)
try:
meeplib.load()
except:
print "did not load"
# done.
# print "No Initiialize"
print "INITIALIZED /n/n/n/n YES"
class MeepExampleApp(object):
"""
WSGI app object.
"""
def index(self, environ, start_response):
start_response("200 OK", [('Content-type', 'text/html')])
cookie = environ.get("HTTP_COOKIE")
if cookie is None or len(cookie)==9:
username2 = ''
loggedInMessage="Not Logged IN"
else:
username2 = cookie[9:]
username2=session_get(c,username2)
loggedInMessage = 'You are logged in as user: %s' % (username2,)
if username2=='':
return [ render_page('index.html', username="NONE") ]
else:
return [ render_page('index.html', username=username2) ]
def login(self, environ, start_response):
#sqlstuff
c.execute('''CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY ,username TEXT,cookie TEXT UNIQUE,created DATETIME)''')
username = 'COOKIEZNAMNAM'
userCookie=session_login(c,username)
print "THE COOKIE",userCookie
usernameDB=session_get(c,userCookie)
print "THE USERNAMEDB ",usernameDB
#end sql stuff
u = meeplib.User('test', 'foo',-1)
# retrieve user
user = meeplib.get_user(username)
# set content-type
headers = [('Content-type', 'text/html')]
cookie_name, cookie_val = meepcookie.make_set_cookie_header('username',userCookie) #pass the cookie out, use it to check if somone is logged in
print "COOKIE_VAL"+cookie_val
print type(cookie_val)
headers.append((cookie_name, cookie_val))
# send back a redirect to '/'
k = 'Location'
v = '/'
headers.append((k, v))
#start_response('302 Found', headers)
# return "no such content"
#headers = [('Content-type', 'text/html')]
start_response("200 OK", headers)
return [ render_page('login.html') ]
def login_action(self, environ, start_response):
# print environ['wsgi.input']
form = cgi.FieldStorage(fp=environ['QUERY_STRING'], environ=environ)
login = form['login'].value
password = form['password'].value
#generate random session id
## db = MySQLdb.connect(db='cse491') ##SQL
## c=db.cursor()
## c.execute('CREATE TABLE IF NOT EXISTS LOGINS(Login varchar(10) Primary key, Password varchar(10), session INTEGER)')
## c.execute('INSERT INTO LOGINS ??login,password, session')
headers = [('Content-type', 'text/html')]
headers.append(('Location', '/m/list'))
#append session to headers, keep session in all headers? check to see if session in database on every page
start_response("302 Found", headers)
return ["message added"]
def logout(self, environ, start_response):
headers = [('Content-type', 'text/html')]
cookie_name, cookie_val = meepcookie.make_set_cookie_header('username','')
cookie = environ.get("HTTP_COOKIE")
username2 = cookie[9:]
print "USERNAME2 IN LOGOUT" + username2
session_delete(c,username2)
username2=session_get(c,username2)
headers.append((cookie_name, cookie_val))
# send back a redirect to '/'
k = 'Location'
v = '/'
headers.append((k, v))
start_response('302 Found', headers)
return "no such content"
def list_search(self, environ, start_response):
# print "ENVIRON", environ
results=meeplib.get_search_results()
s = []
#print "RESULTS"
# print results
for result in results:
s.append(meeplib.get_message(result))
## m=meeplib.get_message(result)
## s.append('id: %d<p>' % (m.id,))
## s.append('title: %s<p>' % (m.title))
## s.append('message: %s<p>' % (m.post))
## try:
## s.append('author: %s<p>' % (m.author.username))
## except:
## s.append('author: %s<p>' % (m.author))
## s.append("<a href='/m/post_reply?id="+str(m.id)+"'>Reply</a><p>")
## if meeplib.has_replies(m.id):
## s.append('<dd>Replies:<hr />')
## for r in meeplib.get_replies(m.id):
## s.append('<dd>%s<p>' % (r))
## s.append('</dd>')
##
## s.append('<hr>')
#TODO MAKE IT DO SEARCH
# s.append("<form action='delete_action' method='POST'>Delete a Message?<br> Message ID: <input type='text' name='id'><input type='submit'>Delete</form>")
headers = [('Content-type', 'text/html')]
start_response("200 OK", headers)
# s.append("<form action='search_action' method='POST'>Search for Messages?<br> Message ID: <input type='text' name='text'><input type='submit'>Delete</form>")
return [ render_page('search_messages.html', messages=s, meeplib=meeplib) ]
return ["".join(s)]
def list_messages(self, environ, start_response):
# time.sleep(10)
messages = meeplib.get_all_messages()
## s = []
## s.append('<hr>')
## for m in messages:
## print m.id
## s.append('id: %d<p>' % (m.id,))
## s.append('title: %s<p>' % (m.title))
## s.append('message: %s<p>' % (m.post))
## print "M",m
## try:
## s.append('author: %s<p>' % (m.author.username))
## except:
## s.append('author: %s<p>' % (m.author))
##
##
##
##
##
## s.append("<a href='/m/post_reply?id="+str(m.id)+"'>Reply</a><p>")
## if meeplib.has_replies(m.id):
## s.append('<dd>Replies:<hr />')
## for r in meeplib.get_replies(m.id):
## s.append('<dd>%s<p>' % (r))
## s.append('</dd>')
##
## s.append('<hr>')
# s.append("<form action='delete_action' method='POST'>Delete a Message?<br> Message ID: <input type='text' name='id'><input type='submit'>Delete</form>")
headers = [('Content-type', 'text/html')]
start_response("200 OK", headers)
#s.append("<form action='search_action' method='POST'>Search for Messages?<br> Message ID: <input type='text' name='text'><input type='submit'>Delete</form>")
return [ render_page('list_messages.html', messages=messages, meeplib=meeplib) ]
#TODO MAKE IT SHOW REPLIES
#return ["".join(s)]
def add_message(self, environ, start_response):
headers = [('Content-type', 'text/html')]
start_response("200 OK", headers)
return [ render_page('add_message.html') ]
def search_message_action(self, environ, start_response):
print "searchaction"
print environ['wsgi.input']
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
text=form['text'].value
searchlist=meeplib.search_message_dict(text)
headers = [('Content-type', 'text/html')]
headers.append(('Location', '/m/search'))
start_response("302 Found", headers)
return ["message deleted"]
############################
def delete_message(self, environ, start_response):
headers = [('Content-type', 'text/html')]
start_response("200 OK", headers)
return """<form action='delete_action' method='POST'>Message:<input type='text' name='message'><br><input type='submit'></form>"""
def delete_message_action(self, environ, start_response):
print "deleteaction"
print environ['wsgi.input']
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
message=int(form['id'].value)
messages = meeplib.get_all_messages()
# meeplib.delete_message(messages[0])
meeplib.delete_message(messages[message])
headers = [('Content-type', 'text/html')]
headers.append(('Location', '/m/list'))
start_response("302 Found", headers)
return ["message deleted"]
###############################
def add_message_action(self, environ, start_response):
# print environ['wsgi.input']
form = cgi.FieldStorage(fp=environ['QUERY_STRING'], environ=environ)
title = form['title'].value
message = form['message'].value
username = 'test'
user = meeplib.get_user(username)
msgid=meeplib._get_next_message_id()
new_message = meeplib.Message(title, message, user,-1)
meeplib.saveMSG()
#meeplib.delete_message(new_message)
headers = [('Content-type', 'text/html')]
headers.append(('Location', '/m/list'))
start_response("302 Found", headers)
return ["message added"]
def add_reply_action(self, environ, start_response):
print environ['wsgi.input']
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
print form
reply = form['reply'].value
mId = form['message_id'].value
meeplib.add_reply(int(mId), reply)
meeplib.saveREPLY()
headers = [('Content-type', 'text/html')]
headers.append(('Location', '/m/list'))
start_response("302 Found", headers)
return ["reply added"]
def delete_message(self, environ, start_response):
headers = [('Content-type', 'text/html')]
start_response("200 OK", headers)
return """<form action='delete_action' method='POST'>id: <input type='text' name='id'><br><input type='submit'></form>"""
def delete_message_action(self, environ, start_response):
print environ['wsgi.input']
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
id = int(form['id'].value)
print id, ' A';
meeplib.delete_message(meeplib.get_message(id))
meeplib.delete_reply(id)
meeplib.saveMSG()
meeplib.saveREPLY()
headers = [('Content-type', 'text/html')]
headers.append(('Location', '/'))
start_response("302 Found", headers)
return ["message deleted"]
def IDTEST (self, environ, start_response):
print environ['wsgi.input']
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ)
# id = int(form['id'].value)
# print id, ' A';
meeplib._get_next_user_id()
headers = [('Content-type', 'text/html')]
headers.append(('Location', '/'))
start_response("302 Found", headers)
return ["message deleted"]
def __call__(self, environ, start_response):
# store url/function matches in call_dict
call_dict = { '/': self.index,
'/login': self.login,
'/logout': self.logout,
'/m/list': self.list_messages,
'/m/search': self.list_search,
'/m/add': self.add_message,
'/m/login_action': self.login_action,
'/m/add_action': self.add_message_action,
'/m/delete': self.delete_message,
'/m/delete_action': self.delete_message_action,
'/m/search_action': self.search_message_action,
'/m/post_reply' : self.post_reply,
'/m/add_reply_action' : self.add_reply_action,
'/m/IDTEST' : self.IDTEST,
'/meep.css': FileServer("files/meep.css"),
'/charmander': FileServer("files/charmander.jpg")
}
# see if the URL is in 'call_dict'; if it is, call that function.
url = environ['PATH_INFO']
fn = call_dict.get(url)
print "THE URL", url
if fn is None:
start_response("404 Not Found", [('Content-type', 'text/html')])
return ["Page not found."]
try:
print "FN", fn
return fn(environ, start_response)
except:
tb = traceback.format_exc()
x = "<h1>Error!</h1><pre>%s</pre>" % (tb,)
print "FN", fn
print "X", x
status = '500 Internal Server Error'
start_response(status, [('Content-type', 'text/html')])
return [x]
def post_reply(self, environ, start_response):
#Get message id
qString = cgi.parse_qs(environ['QUERY_STRING'])
mId = qString.get('id', [''])[0]
headers = [('Content-type', 'text/html')]
start_response("200 OK", headers)
#brownie points below
x = """<form action='add_reply_action' method='POST'><input type='hidden' value='%s' name='message_id'>Reply:<input type='text' name='reply'><input type='submit'></form>""" % (mId)
return x