-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
207 lines (174 loc) · 6.67 KB
/
server.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
from tornado.ncss import Server, ncssbook_log
import user
from datetime import datetime
from db import Category, Meme, Person, Upvote
import base64
from template import render_file
import os
def format_time(date):
from datetime import datetime, timedelta
import dateutil.parser
try:
date = dateutil.parser.parse(date) # get ISO 8601 as a datetime object
date += timedelta(hours = 11) # add 11 hours
cur_time = datetime.utcnow()
cur_time += timedelta(hours = 11)
if abs(cur_time.hour - date.hour) <= 1:
return "Less than 1 hour ago"
else:
return date.strftime('%I:%M:%S %d/%m/%Y')
except ValueError:
return date
def get_user_from_cookie(response):
cookie = response.get_secure_cookie('loggedin')
if cookie:
cookie = cookie.decode('UTF-8')
cookie_split = str(cookie).split(',')
return cookie_split[1]
else:
return 'Username not defined in cookie'
def nearby_handler(response):
dp = 'fixme'
photo_list = Meme.get_memes_for_category(3)
rendered = render_file("pages/nearby.html", {
"dp": dp,
"photo_list": photo_list,
})
response.write(rendered)
def photo_save(user: str, caption: str, lat: str, long: str, base64blob):
"This function will take information about a photo and save it to a location."
current_time = datetime.utcnow().isoformat()
Meme.create_meme_post(base64blob, caption, lat, long, user, current_time, 3)
def login_handler(response):
user.login_handler(response)
def logout_handler(response):
user.logout_handler(response)
def requires_login(handler):
def handler_(response, *args, **kwargs):
cookie = response.get_secure_cookie('loggedin')
if cookie:
cookie = cookie.decode('UTF-8')
cookie_split = str(cookie).split(',')
if cookie_split[0] == 'True':
handler(response, *args, **kwargs)
else:
response.redirect('/login')
else:
response.redirect('/login')
return handler_
def index_handler(response):
response.redirect('/feed')
@requires_login
def profile_handler(response, user):
profile_picture = '/static/test.png'
person = Person.get_user_by_username(user)
if not person:
response.write('No user found with that name')
return
var_dict = {
'person': person
}
rendered = render_file(os.path.join('pages', 'profile.html'), var_dict)
response.write(rendered)
def signup_handler(response):
user.signup_handler(response)
#------------------
def meme_image(response, filename):
response.set_header('Content-Type', 'image/png')
f = open('files/' + filename, 'rb')
photo = f.read()
response.write(photo)
def template_example(response):
"""An unused endpoint giving a demo of the template engine."""
variables = {
'title': 'A template example',
'friends': ['Bella', 'Joel', 'Jaxon', 'Owen']
}
rendered = render_file('pages/example_body.html', variables)
response.write(rendered)
@requires_login
def upload_handler(response):
"""Handles displaying the upload form, as well as recieving the data and
entering it into the database."""
if response.get_field("caption"):
# The "username" field is not empty, so we are recieving data
username = get_user_from_cookie(response)
caption = response.get_field('caption')
latitude = response.get_field('lat')
longitude = response.get_field('long')
if response.get_field('resized_image'):
base64blob = response.get_field('resized_image')
print("Got resized meme photo, of %d bytes in base64" % len(base64blob))
else:
filename, content_type, photo_blob = response.get_file('photo')
base64blob = "data:{};base64,".format(content_type) + base64.b64encode(photo_blob).decode('ascii')
print("Got non-resized meme photo, of %d bytes in base64" % len(base64blob))
# Save to the database.
photo_save(username, caption, latitude, longitude, base64blob)
# Redirect to the feed, where they should see their new photo!
response.redirect('/feed')
else:
# We need to display an upload form.
variables = {
'meme_of_week_img': '/static/memeOTW.jpg'
}
rendered = render_file('pages/upload.html', variables)
response.write(rendered)
def index_example(response):
response.write(render_file('pages/index.html', {}))
def nearby_handler(response):
dp = 'https://www.transparenthands.org/wp-content/themes/transparenthands/images/donor-icon.png'
photo_list = Meme.get_memes_for_category(3)
rendered = render_file("pages/nearby.html", {
"dp": dp,
"photo_list": photo_list
})
response.write(rendered)
# imgsrc = 'http://i0.kym-cdn.com/entries/icons/mobile/000/006/199/responsibility12(alternate).jpg'
def feed_handler(response):
dp = 'http://i0.kym-cdn.com/profiles/icons/big/000/132/880/awesome%20face%20shrug.jpg'
photo_list = Meme.get_memes_for_category(3)
check_upvotes_l = lambda x: check_upvote_l(x)
imglink = "/post"
time_func = lambda x: format_time(x)
rendered = render_file("pages/feed.html", {
"dp": dp,
"photo_list": photo_list,
"imglink": imglink,
"time_format": time_func,
'check_upvotes': check_upvotes_l
})
response.write(rendered)
def upvote_meme(response, memeid):
Upvote.create_upvote(0, 0, int(memeid))
response.write("Success!!")
def check_upvote(response, memeid):
upvote_data = Upvote.get_upvotes_for_memes(memeid)
response.write("Yay!!")
response.write(str(len(upvote_data)))
def check_upvote_l(memeid):
upvote_data = Upvote.get_upvotes_for_memes(memeid)
return str(len(upvote_data))
def post_handler(response, i):
dp = 'http://i0.kym-cdn.com/profiles/icons/big/000/132/880/awesome%20face%20shrug.jpg'
rendered = render_file("pages/post.html", {
"dp": dp,
"meme": Meme.get_meme_from_id(i)
})
response.write(rendered)
server = Server()
server.register('/', index_handler)
server.register('/feed', feed_handler)
server.register('/upload', upload_handler)
server.register('/login', login_handler)
server.register('/logout', logout_handler)
server.register('/signup', signup_handler)
server.register(r'/post/(.+)', post_handler)
#---------------
server.register(r'/profile/(.+)', profile_handler)
server.register('/index_example', index_example)
server.register('/nearby', nearby_handler)
server.register(r'/upvote_meme/(.+)', upvote_meme)
server.register(r'/check_upvote/(.+)', check_upvote)
if __name__ == "__main__":
server.run()