python Tornado框架的使用示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python Tornado框架的使用示例

RainBol   2020-10-19 我要评论

Tornado是一个python的开源web框架,它比django要轻量级到多,也没有什么组件,只有运用到对应到业务场景下我才使用这个框架,它是单进程单线程到异步非阻塞模型,适用与长连接长轮巡,高并发,异步非阻塞

安装:

pip install tornado

View层

'''
@File    : views_service.py
@Copyright : rainbol
@Date    : 2020/8/31
@Desc    :
'''
import threading
import time
import tornado.web
import tornado
import tornado.ioloop
import tornado.web
import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import random

all_count = 0
big_list = {}


class ServiceHandler(tornado.web.RequestHandler):
  executor = ThreadPoolExecutor(20) # 最大线程数 必须定义一个executor的属性,然后run_on_executor装饰器才会有用。

  @run_on_executor # 在这个方法下,线程内运行;query函数被run_on_executor包裹(语法糖),将该函数的执行传递给线程池executor的线程执行,优化了处理耗时性任务,以致达到不阻塞主线程的效果。
  def time_demo(self, tid, uid):
    time.sleep(tid)
    threading_id = threading.current_thread().ident
    big_list[uid] = threading_id

  @tornado.gen.coroutine # 异步、协程处理;增加并发量
  def post(self):
    global all_count
    all_count += 1
    uid = str(uuid4())
    yield self.time_demo(random.randint(1, 100), uid) # 模拟业务处理,使用yield来实现异步阻塞请求
    r = {'status': 'True', '线程id': '%s' % big_list[uid], "count": all_count}

    self.write(tornado.escape.json_encode(r)) # 写入返回信息写入response
    self.finish() # 结束服务

  def get(self):
    return self.post()

__init__.py

'''
@File    : __init__.py
@Copyright : rainbol
@Date    : 2020/8/31
@Desc    :
'''
import tornado.web # web框架
import tornado.httpserver # http服务
import tornado.ioloop # 输入输出事件循环
import tornado.options # 配置工具
from tornado.options import options, define
from app.config import configs
from app.urls import urls
define('port', default=8000, type=int, help='运行端口')


# 自定义应用
class CustomApplication(tornado.web.Application):
  def __init__(self): # 重写构造方法
    # 指定路由规则
    handlers = urls
    # 指定配置文件
    settings = configs
    super(CustomApplication, self).__init__(handlers=handlers, **settings)


# 定义服务
def create_server():
  # 允许在命令行中启动
  #tornado.options.parse_command_line()
  # 创建http服务
  http_server = tornado.httpserver.HTTPServer(
    CustomApplication() # 注意要实例化
  )
  # 绑定监听的端口
  http_server.listen(options.port)
  # 启动输入输出事件循环
  tornado.ioloop.IOLoop.instance().start()
'''
@File    : manage.py
@Copyright : rainbol
@Date    : 2020/8/31
@Desc    :
'''
from app.views import create_server



if __name__ == '__main__':
  create_server()

路由

from app.views.views_index import IndexHandler as index
from app.views.views_service import ServiceHandler as service

# 配置路由和配置到映射规则

urls = [
  (r"/index", index),
  (r"/demo", service),
]

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们