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从入门到精通(DAY 1)

python从入门到精通(DAY 1)

1、要点    (1) 在C语言中没有字符串,只有字符,    在python中的字符串hello,在C语言中是以字符数组在内存存放['h','e...

Python实现的简单发送邮件脚本分享

近来有些东西需要监控报警发邮件,然后在网上找了点材料,自己写了一个简单发送邮件的脚本,主要就是运用python的smtplib模块,分享给大家看一下: 复制代码 代码如下: #!/usr...

Python SQLite3数据库操作类分享

接触Python时间也不是很长的,最近有个项目需要分析数据,于是选用Python为编程语言,除了语言特性外主要还是看重Python对于SQLite3数据库良好的支持能力了,因为需要灵活处...

使用python开发vim插件及心得分享

使用python开发vim插件及心得分享

vim有各种强大的插件,这不仅归功于其提供的用来编写插件的脚本语言vimL,还得益于它良好的接口实现,从而支持python等语言编写插件。当vim编译时带有+python特性时就能使用p...

wxPython:python首选的GUI库实例分享

wxPython:python首选的GUI库实例分享

wxPython是Python语言的一套优秀的GUI图形库,允许Python程序员很方便的创建完整的、功能健全的GUI用户界面。 wxPython是作为优秀的跨平台GUI库wxWidge...