Skip to content

Instantly share code, notes, and snippets.

@ssbozy
Created October 2, 2015 16:36
Show Gist options
  • Save ssbozy/698109ba86f12d2ef9ff to your computer and use it in GitHub Desktop.
Save ssbozy/698109ba86f12d2ef9ff to your computer and use it in GitHub Desktop.
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"
@ssbozy
Copy link
Author

ssbozy commented Oct 2, 2015

autoreload is same as debug. However to use only a few features of debug, you can switch autoreload to False and debug to True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment