-
Notifications
You must be signed in to change notification settings - Fork 1
/
blog.py
267 lines (192 loc) · 7.84 KB
/
blog.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
import bottle
from pymongo import Connection
import cgi
import re
import datetime
import random
import hmac
import user
import json
# inserts the blog entry and returns a permalink for the entry
def insert_entry(title, post):
print "inserting blog entry", title, post
connection = Connection("mongodb://production:10gen@staff.mongohq.com:10038/erlichson")
db = connection.erlichson
posts = db.posts
exp = re.compile('\W') # match anything not alphanumeric
whitespace = re.compile('\s')
temp_title = whitespace.sub("_",title)
permalink = exp.sub('', temp_title)
post = {"title": title,
"post": post,
"permalink":permalink,
"date": datetime.datetime.utcnow()}
posts.insert(post)
return permalink
@bottle.route('/')
def index():
connection = Connection("mongodb://production:10gen@staff.mongohq.com:10038/erlichson")
db = connection.erlichson
students = db.students
student = students.find_one()
return '<b>Hello %s!</b>' % student['name']
@bottle.route('/blog')
def blog_index():
connection = Connection("mongodb://production:10gen@staff.mongohq.com:10038/erlichson")
db = connection.erlichson
posts = db.posts
cur = posts.find().sort('date', direction=-1).limit(10)
l=[]
for post in cur:
l.append({'title':post['title'], 'content':post['post'], 'post_date':post['date'], 'permalink':post['permalink']})
return bottle.template('blog_template', dict(myposts=l))
@bottle.route('/blog/.json')
def blog_index_json():
connection = Connection("mongodb://production:10gen@staff.mongohq.com:10038/erlichson")
db = connection.erlichson
posts = db.posts
cur = posts.find().sort('date', direction=-1)
l=[]
for post in cur:
mydate = post['date']
dates = mydate.strftime("%A, %d. %B %Y %I:%M%p")
l.append({'subject':post['title'], 'content':post['post'], 'created':dates})
bottle.response.content_type = "application/json"
return json.dumps(l)
# gets called both for regular requests and json requests
@bottle.get("/blog/post/<permalink>")
def show_post(permalink="notfound"):
connection = Connection("mongodb://production:10gen@staff.mongohq.com:10038/erlichson")
db = connection.erlichson
posts = db.posts
permalink = cgi.escape(permalink)
# determine if its a json request
path_re = re.compile(r"^([^\.]+).json$")
json_request = False
m = path_re.match(permalink)
if (m):
print "this is a json request"
json_request = True
permalink = m.group(1)
print "about to quer on permalink = ", permalink
post = posts.find_one({'permalink':permalink})
if post == None:
bottle.redirect("/blog/post_not_found")
print "date of entry is ", post['date']
if json_request:
mydate = post['date']
dates = mydate.strftime("%A, %d. %B %Y %I:%M%p")
post = dict(subject=post['title'], content=post['post'], created=dates)
bottle.response.content_type = "application/json"
return json.dumps(post)
else:
return bottle.template("entry_template", dict(mdate=post['date'],title=post['title'], content=post['post']))
@bottle.get("/blog/post_not_found")
def post_not_found():
return "Sorry, post not found"
# how new posts bottle.get made
@bottle.get('/blog/newpost')
@bottle.view('newpost_template')
def get_newpost():
return dict(subject="", content="",errors="")
@bottle.post('/blog/newpost')
def post_newpost():
title = bottle.request.forms.get("subject")
post = bottle.request.forms.get("content")
if (title == "" or post == ""):
errors="Post must contain a title and blog entry"
return bottle.template("newpost_bottle.template", dict(subject=cgi.escape(title, quote=True),
content=cgi.escape(post, quote=True), errors=errors))
# looks like a good entry
permalink=insert_entry(title, post)
# now bottle.redirect to the blog permalink
bottle.redirect("/blog/post/" + permalink)
@bottle.get('/blog/signup')
def present_signup():
return bottle.template("signup",
dict(username="", password="",
password_error="",
email="", username_error="", email_error="",
verify_error =""))
@bottle.get('/blog/login')
def present_login():
return bottle.template("login",
dict(username="", password="",
login_error=""))
@bottle.post('/blog/login')
def process_login():
username = bottle.request.forms.get("username")
password = bottle.request.forms.get("password")
userRecord = {}
if (user.validate_login(username, password, userRecord)):
session_id = user.start_session(userRecord['uid'])
cookie = user.make_secure_val(str(int(session_id)))
bottle.response.set_cookie("session", cookie)
bottle.redirect("/blog/welcome")
else:
return bottle.template("login",
dict(username=cgi.escape(username), password="",
login_error="Invalid Login"))
@bottle.get('/blog/logout')
def process_logout():
cookie = bottle.request.get_cookie("session")
if (cookie == None):
print "no cookie..."
bottle.redirect("/blog/signup")
else:
session_id = user.check_secure_val(cookie)
if (session_id == None):
print "no secure session_id"
bottle.redirect("/blog/signup")
else:
# remove the session
user.end_session(session_id)
print "clearing the cookie"
bottle.response.set_cookie("session",";Path=\/")
bottle.redirect("/blog/signup")
@bottle.post('/blog/signup')
def process_signup():
email = bottle.request.forms.get("email")
username = bottle.request.forms.get("username")
password = bottle.request.forms.get("password")
verify = bottle.request.forms.get("verify")
# set these up in case we have an error case
errors = {'username':cgi.escape(username), 'email':cgi.escape(email)}
if (user.validate_signup(username, password, verify, email, errors)):
uid = user.newuser(username, password, email)
if (uid == None):
# this was a duplicate
errors['username_error'] = "Username already in use. Please choose another"
return bottle.template("signup", errors)
session_id = user.start_session(uid)
cookie= user.make_secure_val(str(int(session_id)))
bottle.response.set_cookie("session",cookie)
bottle.redirect("/blog/welcome")
else:
return bottle.template("signup", errors)
@bottle.get("/blog/welcome")
def present_welcome():
# check for a cookie, if present, then extract value
cookie = bottle.request.get_cookie("session")
if (cookie == None):
print "no cookie..."
bottle.redirect("/blog/signup")
else:
session_id = user.check_secure_val(cookie)
if (session_id == None):
print "no secure session_id"
bottle.redirect("/blog/signup")
else:
# look up username record
session = user.get_session(session_id)
if (session == None):
print "no valid session"
bottle.redirect("/blog/signup")
username = user.uid_to_username(session['uid'])
if username == None:
print "Database error looking up uid"
bottle.redirect("/blog/signup")
return bottle.template("welcome", {'username':username})
bottle.debug(True)
bottle.run(host='ec2-174-129-129-215.compute-1.amazonaws.com', port=8082)
#bottle.run(host='localhost', port=8082)