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

yipeiwu_com6年前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脚本代码

我就废话不多说,直接上代码吧: # -*- coding: utf-8 -*- import os out=os.system('netstat -aon|findstr "25"'...

python中字符串变二维数组的实例讲解

python中字符串变二维数组的实例讲解

有一道算法题题目的意思是在二维数组里找到一个峰值。要求复杂度为n。 解题思路是找田字(四边和中间横竖两行)中最大值,用分治法递归下一个象限的田字。 在用python定义一个二维数组时可以...

python求众数问题实例

本文实例讲述了python求众数问题的方法,是一个比较典型的应用。分享给大家供大家参考。具体如下: 问题描述: 多重集中重数最大的元素称为众数...就是一个可以有重复元素的集合,在这个集...

python 进程 进程池 进程间通信实现解析

1.python 中创建进程的两种方式: from multiprocessing import Process import time def test_(): print '...

详解Python连接MySQL数据库的多种方式

上篇文章分享了windows下载mysql5.7压缩包配置安装mysql 后续可以选择 ①在本地创建一个数据库,使用navicat工具导出远程测试服务器的数据库至本地,用于学习操作,且不...