1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # --------------------------------------- 4 # email : gengjie@outlook.com 5 # Create Time: 4/9/16 20:58 6 # ---------------------------------------- 7 8 import json 9 import time 10 from tornado.web import RequestHandler 11 from tornado.web import Application 12 from tornado.ioloop import IOLoop 13 from tornado.log import app_log 14 15 16 class ArgumentHandler(RequestHandler): 17 '''return last name value''' 18 def get(self): 19 self.write('hello {0}'.format(self.get_argument('name'))) 20 21 22 class ArgumentsHandler(RequestHandler): 23 '''return all name args''' 24 def get(self): 25 self.write('hello {0}'.format(', '.join(self.get_arguments('name')))) 26 27 28 class BodyHandler(RequestHandler): 29 '''Get body''' 30 def post(self): 31 body = json.loads(self.request.body.decode()) 32 app_log.warning(self.request.body.decode()) 33 self.write('hello {0}'.format(body['name'])) 34 35 36 class PathArgsHandler(RequestHandler): 37 def get(self, *args, **kwargs): 38 self.write('hello {0}'.format(args[0])) 39 40 41 class PathKwargsHandler(RequestHandler): 42 def get(self, *args, **kwargs): 43 self.write('hello {0}'.format(kwargs['name'])) 44 45 46 class RemoteHandler(RequestHandler): 47 '''Get client Ip''' 48 def get(self, *args, **kwargs): 49 self.write(self.request.remote_ip) 50 51 52 class FobiddenHandler(RequestHandler): 53 def get(self, *args, **kwargs): 54 self.set_status(403) 55 self.write('forbidden') 56 57 58 class CustomStatusHandler(RequestHandler): 59 def get(self, *args, **kwargs): 60 self.set_status(498, reason='Custom Error.') 61 self.finish() 62 63 64 class HeaderHandler(RequestHandler): 65 def get(self, *args, **kwargs): 66 self.set_header('X-Header', 'Set_001') 67 self.add_header('X-Header', 'Add_001') 68 self.write('hello head') 69 70 71 class MultWriteHandler(RequestHandler): 72 def get(self, *args, **kwargs): 73 self.write('start ') 74 self.flush() 75 for x in range(10): 76 self.write('{0} '.format(x)) 77 self.flush() 78 time.sleep(0.1) 79 self.finish('complete ') 80 81 82 if __name__ == '__main__': 83 app = Application( 84 [ 85 (r'/', ArgumentHandler), 86 (r'/args', ArgumentsHandler), 87 (r'/body', BodyHandler), 88 (r'/path/args/(.*)', PathArgsHandler), 89 (r'/path/kwargs/(?P<name>.*)', PathKwargsHandler), 90 (r'/ip', RemoteHandler), 91 (r'/403', FobiddenHandler), 92 (r'/498', CustomStatusHandler), 93 (r'/head', HeaderHandler), 94 (r'/multi', MultWriteHandler) 95 ] 96 ) 97 app.listen(port=8001, address='0.0.0.0') 98 IOLoop.current().start()