-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
101 lines (83 loc) · 2.51 KB
/
main.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
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import json
from model.dweet import Dweet
from utils.base_handler import BaseHandler
from tornado.options import define, options
define("port", default=80, type=int)
dweets = {}
def get_last_dweet(thing):
return dweets[thing][-1]
def get_last_dweets(thing, size=100):
size = min(size, len(dweets[thing]))
print(size)
return dweets[thing][-size:]
def save_dweet(thing, content):
dweet = Dweet(thing, content)
if thing in dweets:
dweets[thing].append(dweet)
else:
dweets[thing] = [dweet]
return dweet
class PostDweet(BaseHandler):
def post(self, thing):
try:
content = tornado.escape.json_decode(self.request.body)
dweet = save_dweet(thing, content)
response = {
"this": "succeeded",
"by": "dweeting",
"the": "dweet",
"with": [dweet.__dict__()]
}
self.write(response)
except json.decoder.JSONDecodeError:
self.set_status(400)
self.finish("Bad JSON.")
class GetDweet(BaseHandler):
def get(self, thing):
try:
dweet = get_last_dweet(thing)
response = {
"this": "succeeded",
"by": "getting",
"the": "dweets",
"with": [dweet.__dict__()]
}
self.write(response)
except:
self.set_status(404)
self.finish("No dweet found.")
class GetDweets(BaseHandler):
def get(self, thing):
try:
print("tab")
dweets = get_last_dweets(thing)
response = {
"this": "succeeded",
"by": "getting",
"the": "dweets",
"with": [dweet.__dict__() for dweet in dweets]
}
self.write(response)
except:
self.set_status(404)
self.finish("No dweet found.")
class GetPing(BaseHandler):
def get(self):
self.write("Pong.")
def main():
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/ping", GetPing),
(r"/dweet/for/([^/]+)", PostDweet),
(r"/get/latest/dweet/for/([^/]+)", GetDweet),
(r"/get/dweets/for/([^/]+)", GetDweets),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()