Tornado高并发处理方法实例代码

yipeiwu_com5年前Python基础

本文主要分享的是一则关于Tornado高并发处理方法的实例,具体如下:

#!/bin/env python
# -*- coding:utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import time
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)


class SleepHandler(tornado.web.RequestHandler):
  executor = ThreadPoolExecutor(2)

  @tornado.web.asynchronous
  @tornado.gen.coroutine
  def get(self):
    # 假如你执行的异步会返回值被继续调用可以这样(只是为了演示),否则直接yield就行
    res = yield self.sleep()
    self.write("when i sleep %s s" % res)
    self.finish()

  @run_on_executor
  def sleep(self):
    time.sleep(5)
    return 5


class JustNowHandler(tornado.web.RequestHandler):
  def get(self):
    self.write("i hope just now see you")


if __name__ == "__main__":
  tornado.options.parse_command_line()
  app = tornado.web.Application(handlers=[
      (r"/sleep", SleepHandler), (r"/justnow", JustNowHandler)])
  http_server = tornado.httpserver.HTTPServer(app)
  http_server.listen(options.port)
  tornado.ioloop.IOLoop.instance().start()

总结

以上就是本文关于Tornado高并发处理方法实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python实现K近邻回归,采用等权重和不等权重的方法

如下所示: from sklearn.datasets import load_boston boston = load_boston() from sklearn.cros...

用matplotlib画等高线图详解

用matplotlib画等高线图详解

等高线图是在地理课中讲述山峰山谷时绘制的图形,在机器学习中也会被用在绘制梯度下降算法的图形中。 因为等高线的图有三个信息:x,y以及x,y所对应的高度值。 这个高度值的计算我们用一个函数...

Python编程实现使用线性回归预测数据

Python编程实现使用线性回归预测数据

本文中,我们将进行大量的编程——但在这之前,我们先介绍一下我们今天要解决的实例问题。 1) 预测房子价格 房价大概是我们中国每一个普通老百姓比较关心的问题,最近几年保障啊,小编这点微末...

python+rsync精确同步指定格式文件

本文实例为大家分享了python+rsync精确同步指定格式文件的具体代码,供大家参考,具体内容如下 # coding: utf-8 #!/usr/bin/env python '...

python 切片和range()用法说明

理解切片基本用法: 首先需要明白,可迭代对象,按照正数索引(正序)是从0开始的,按照负数索引(逆序)是从-1开始的。>>> astring = 'Hello world...