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

相关文章

一个基于flask的web应用诞生 使用模板引擎和表单插件(2)

一个基于flask的web应用诞生 使用模板引擎和表单插件(2)

经过了第一章的内容,已经可以做出一些简单的页面,首先用这种方式做一个登录页面,首先要创建一个login的路由方法: @app.route("/login",methods=["GET...

python中字符串前面加r的作用

本文实例讲述了python中字符串前面加r的作用。分享给大家供大家参考。具体分析如下: 字符串前面加r,表示的意思是禁止字符串转义 >>> print "asfd...

Python代码缩进和测试模块示例详解

前言 Python代码缩进和测试模块是大家学习python必不可少的一部分,本文主要介绍了关于Python代码缩进和测试模块的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看...

Python实现配置文件备份的方法

本文实例讲述了Python实现配置文件备份的方法。分享给大家供大家参考。具体如下: 这里平台为Linux: #!/usr/bin/python #Author:gdlinjianyi...

用python实现对比两张图片的不同

用python实现对比两张图片的不同

from PIL import Image from PIL import ImageChops def compare_images(path_one, path_two,...