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只能調用一次web