-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
227 lines (189 loc) · 6.87 KB
/
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
import os, time
from datetime import datetime, date
import pytz
from tornado import websocket, web, ioloop, gen
import simplejson as json
# the Metro Network won't allow the process to contact Sentry, ugh
# from raven.contrib.tornado import AsyncSentryClient, SentryMixin
# private variables
from conf import cookie_secret, sentry_key, PORT, ADDRESS
from utils import getSuffix
# create logger
import logging
logger = logging.getLogger('server')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create log formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# logfile
hdlr = logging.FileHandler('logs/server.log')
hdlr.setLevel(logging.WARNING)
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
theclients = []
settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
"cookie_secret": cookie_secret,
# "login_url": "/login",
# "xsrf_cookies": True,
}
# raven/sentry stuff
# this is for Raven
# class UncaughtExceptionHandler(web.RequestHandler):
#
# def get(self):
# 1 / 0
class AsyncMessageHandler(web.RequestHandler):
@web.asynchronous
@gen.engine
def get(self):
self.write("You requested the main page")
# yield gen.Task(
# # self.captureMessage, "Request for main page served"
# logger.info("Request for main page served")
# )
self.finish()
# class AsyncExceptionHandler(SentryMixin, web.RequestHandler):
class AsyncExceptionHandler(web.RequestHandler):
@web.asynchronous
@gen.engine
def get(self):
try:
raise ValueError()
except Exception as e:
warningmsg = "%s | %s" %(e.message, e.args)
logger.info(warningmsg)
# response = yield gen.Task(
# self.captureException, exc_info=True
# )
self.finish()
# class IndexHandler(SentryMixin, web.RequestHandler):
class IndexHandler(web.RequestHandler):
# SUPPORTED_METHODS = ("CONNECT", "GET", "HEAD", "POST", "DELETE", "PATCH", "PUT", "OPTIONS")
SUPPORTED_METHODS = ("CONNECT", "GET", "HEAD", "OPTIONS")
def head(self):
""" Satisfy the Viewsonic browser that this url exists"""
self.finish()
def get(self):
# self.captureMessage("Request for main page served")
# logging
logger.info("Request for main page served")
self.render("index.html")
class SocketHandler(websocket.WebSocketHandler):
def check_origin(self, origin):
logger.info("check_origin: " +repr(origin))
return True
def open(self):
if self not in theclients:
logger.info("opened client: " +repr(self.get_status()))
theclients.append(self)
def on_close(self):
if self in theclients:
logger.info("closed client: " +repr(self.get_status()))
theclients.remove(self)
def on_message(self, message):
logger.info("message received: " +repr(message))
class ApiHandler(web.RequestHandler):
@web.asynchronous
def get(self, *args):
# curl "http://127.0.0.1:8888/api?id=9&value=Henry-Huntington"
self.finish()
id = self.get_argument("id")
value = self.get_argument("value")
data = {"id": id, "value": value}
data = json.dumps(data)
for c in theclients:
c.write_message(data)
@web.asynchronous
def post(self):
raw_data = self.request.body
json_data = json.loads(raw_data)
self.finish()
try:
js = json.loads(json_data)
sorted_meetings = sorted(js['current'], key=lambda k: k['ts'])
except ValueError:
raise tornado.httpserver._BadRequestException(
"Invalid JSON structure."
)
# display today
now = datetime.now()
dayint = datetime.now().day
suffix = getSuffix(dayint)
today = "%s %s%s, %s" % (now.strftime(
"%A %B"), dayint, suffix, datetime.now().year)
mlist = []
postme = True
for i, item in enumerate(sorted_meetings[0:15]):
try:
if item['res_general_desc'] == None:
item['res_general_desc'] = "Untitled Meeting"
# logging
logger.debug("------------" + item['res_general_desc'])
logger.debug(item['room_name'])
logger.debug(item['displaytime'])
d = {}
title = "title_%s" % i
room = "room_%s" % i
t = "time_%s" % i
try:
floorsfx = getSuffix( int(item['room_floor']) )
room_floor = "%s, %s%s floor" %(item['room_name'], item['room_floor'], floorsfx)
except Exception as e:
room_floor = "%s" %(item['room_name'])
# logging
warningmsg = "we don't know the floor for that room | %s | %s" %(e.message, e.args)
logger.warn(warningmsg)
d = {title: item['res_general_desc'],
room: room_floor,
t: item['displaytime'],
}
mlist.append(d)
except Exception as e:
warningmsg = "%s | %s" %(e.message, e.args)
# logging
logger.warn(warningmsg)
postme = False
if (postme):
for d in mlist:
for k, v in d.items():
msg = {"id": k, "value": v}
for c in theclients:
c.write_message(msg)
# now, the metadata
for c in theclients:
c.write_message(
{"id": "lastupdate", "value": "last update: " + js["lastupdate"]})
c.write_message({"id": "display_today", "value": today})
# 2. Create Tornado application
app = web.Application([
(r'/', IndexHandler),
(r'/ws', SocketHandler),
(r'/api', ApiHandler),
(r'/(favicon.ico)', web.StaticFileHandler, {'path': '../'}),
(r'/(rest_api_example.png)', web.StaticFileHandler, {'path': './'}),
], **settings)
# app.sentry_client = AsyncSentryClient(
# sentry_key
# )
# standlone server
if __name__ == '__main__':
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create log formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
logger.info("Tornado sign server server starting...")
# 3. Make Tornado app listen on port
app.listen(port=PORT, address=ADDRESS)
# 4. Start IOLoop
ioloop.IOLoop.instance().start()