这是一个完整的示例Tornado应用程序,该应用程序使用Async HTTP客户端和该
gen.Task模块使事情变得简单。
如果您
gen.Task在文档中了解更多信息,您会发现实际上可以同时调度多个请求。这是使用“龙卷风”的核心思想,即一切都不会阻塞并且仍保持单个进程。
更新: 我添加了一个线程处理程序,以演示如何将工作分派到第二个线程中并在
callback()完成时接收。
import osimport threadingimport tornado.optionsimport tornado.ioloopimport tornado.httpserverimport tornado.httpclientimport tornado.webfrom tornado import genfrom tornado.web import asynchronoustornado.options.define('port', type=int, default=9000, help='server port number (default: 9000)')tornado.options.define('debug', type=bool, default=False, help='run in debug mode with autoreload (default: False)')class Worker(threading.Thread): def __init__(self, callback=None, *args, **kwargs): super(Worker, self).__init__(*args, **kwargs) self.callback = callback def run(self): import time time.sleep(10) self.callback('DONE')class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", IndexHandler), (r"/thread", ThreadHandler), ] settings = dict( static_path = os.path.join(os.path.dirname(__file__), "static"), template_path = os.path.join(os.path.dirname(__file__), "templates"), debug = tornado.options.options.debug, ) tornado.web.Application.__init__(self, handlers, **settings)class IndexHandler(tornado.web.RequestHandler): client = tornado.httpclient.AsyncHTTPClient() @asynchronous @gen.engine def get(self): response = yield gen.Task(self.client.fetch, "http://google.com") self.finish("Google's homepage is %d bytes long" % len(response.body))class ThreadHandler(tornado.web.RequestHandler): @asynchronous def get(self): Worker(self.worker_done).start() def worker_done(self, value): self.finish(value)def main(): tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(tornado.options.options.port) tornado.ioloop.IOLoop.instance().start()if __name__ == "__main__": main()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)