python Tornado框架的使用方法有哪些?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
安装:
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),
]
关于python Tornado框架的使用方法有哪些问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。