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中读写和存储matlab的数据文件(*.mat)

背景 在做deeplearning过程中,使用caffe的框架,一般使用matlab来处理图片(matlab处理图片相对简单,高效),用python来生成需要的lmdb文件以及做test...

Python、Javascript中的闭包比较

同为脚本语言,python和Javascript具有相似的变量作用域,不像php,函数的内部的所有变量和外部都是隔绝的,也就是说,函数要想处理其外部的数据,必须使用参数把需要处理的数据传...

基于python实现高速视频传输程序

今天要说的是一个高速视频流的采集和传输的问题,我不是研究这一块的,没有使用什么算法,仅仅是兴趣导致我很想搞懂这个问题.     1,首先是视频数据[摄像头图...

python实现读取并显示图片的两种方法

在 python 中除了用 opencv,也可以用 matplotlib 和 PIL 这两个库操作图片。本人偏爱 matpoltlib,因为它的语法更像 matlab。 一、matplo...

python正则中最短匹配实现代码

python正则中最短匹配实现代码

下面从一个例子入手: 利用正则表达式解析下面的XML/HTML标签: <composer>Wolfgang Amadeus Mozart</composer>...