from datetime import datetime
import tornado.httpserver
import tornado.web
import tornado.ioloop
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write('ON GET {0}'.format(datetime.now()))
return self.write('ON GET {0}'.format(datetime.now()))
def post(self):
return self.finish('ON POST {0}'.format(datetime.now()))
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r".*", MainHandler),
]
tornado.web.Application.__init__(self, handlers)
if __name__ == "__main__":
port = 8899
application = Application()
http_server = tornado.httpserver.HTTPServer(application, xheaders=True)
http_server.listen(port)
print('Listen on http://localhost:{0}'.format(port))
tornado.ioloop.IOLoop.instance().start()
以上这段代码监听了8899端口, 并把所有地址的请求都让MainHandler来处理, MainHandler对于每个get和post请求都返回一段文字,其中write和finish的区别在于,write可以调用多次,而finish只能调用一次