Created
October 2, 2015 16:36
-
-
Save ssbozy/698109ba86f12d2ef9ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from tornado import httpserver, web, ioloop, options, log | |
from random import random | |
class BaseHandler(web.RequestHandler): | |
'''BaseHandler for all handlers''' | |
def write_error(self, status_code, **kwargs): | |
if status_code == 400: | |
response = {"code":status_code, "message": "Bad Request"} | |
if status_code == 401: | |
response = {"code":status_code, "message": "Unauthorized"} | |
if status_code == 403: | |
response = {"code":status_code, "message":"Forbidden"} | |
if status_code == 404: | |
response = {"code":status_code, "message":"Not Found"} | |
if status_code == 405: | |
response = {"code":status_code, "message":"Method Not Allowed"} | |
if status_code == 408: | |
response = {"code":status_code, "message":"Request Timeout"} | |
if status_code == 500: | |
response = {"code":status_code, "message":"Internal Server Error"} | |
self.write({"response":response}) | |
class IndexHandler(BaseHandler): | |
'''Handles IndexHandler''' | |
def get(self): | |
# send_error() is used to test inherited write_error. | |
# self.send_error(400) | |
self.write({"response":\ | |
{"code":200,"message":"OK","data":"Hello World "+str(random())}\ | |
}) | |
class ErrorHandler(BaseHandler): | |
pass | |
class Application(web.Application): | |
def __init__(self): | |
handlers = [(r'/', IndexHandler), \ | |
(r'/(.*)', ErrorHandler)] | |
settings = {'autoreload':True, \ | |
'compress_response':True} | |
web.Application.__init__(self, handlers, **settings) | |
def main(): | |
options.options.log_file_prefix='/tmp/tornado_sample.log' | |
log.enable_pretty_logging() | |
webserver = httpserver.HTTPServer(Application()).listen(80,address='0.0.0.0') | |
ioloop.IOLoop.instance().start() | |
if __name__ == '__main__': | |
try: | |
main() | |
except KeyboardInterrupt: | |
print "Stopping Webserver" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
autoreload is same as debug. However to use only a few features of debug, you can switch autoreload to False and debug to True