Hello tornado world

0. install tornado

1
pip3 install tornado

1. Write code

Saving those code below as 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2020-04-22 23:35:44
# @Author : Simon (simon.xie@codewalker.me)
# @Link : http://blog.codewalker.me
# @Version : 1.0.0

import tornado.web
import tornado.ioloop

class basicRequestHandler(tornado.web.RequestHandler):
def get(self):
self.write("hello world")
class staticRequestHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')

class queryStringRequestHandler(tornado.web.RequestHandler):
def get(self):
n = int(self.get_argument('n'))
result = 'odd' if n % 2 else 'even'
self.write('ths number {} is {}'.format(n,result))
class resourceRequestHandler(tornado.web.RequestHandler):
def get(self, mid):
self.write("Hey we got id: {}".format(mid))

def main():
app = tornado.web.Application([
(r'/', basicRequestHandler),
(r'/static', staticRequestHandler),
(r'/query', queryStringRequestHandler),
(r'/resource/([0-9]+)', resourceRequestHandler)
])
app.listen(8081)
print('server is turn on and listening port 8081')
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()

2. Run code

1
2
chmod +x server.py
python3 server.py

3. view your first web appliction with tornado

Hit the url with your fever browser

  • http://127.0.0.1:8081/
  • http://127.0.0.1:8081/static
  • http://127.0.0.1:8081/query?n=3
  • http://127.0.0.1:8081/resource/3

EOF
Enjoy
I, simon love this world ❤️