python Tornado框架的使用示例
Tornado是一个python的开源web框架,它比django要轻量级到多,也没有什么组件,只有运用到对应到业务场景下我才使用这个框架,它是单进程单线程到异步非阻塞模型,适用与长连接长轮巡,高并发,异步非阻塞
安装:
pipinstalltornado
View层
'''
@File:views_service.py
@Copyright:rainbol
@Date:2020/8/31
@Desc:
'''
importthreading
importtime
importtornado.web
importtornado
importtornado.ioloop
importtornado.web
importtornado.gen
fromtornado.concurrentimportrun_on_executor
fromconcurrent.futuresimportThreadPoolExecutor
fromuuidimportuuid4
importrandom
all_count=0
big_list={}
classServiceHandler(tornado.web.RequestHandler):
executor=ThreadPoolExecutor(20)#最大线程数必须定义一个executor的属性,然后run_on_executor装饰器才会有用。
@run_on_executor#在这个方法下,线程内运行;query函数被run_on_executor包裹(语法糖),将该函数的执行传递给线程池executor的线程执行,优化了处理耗时性任务,以致达到不阻塞主线程的效果。
deftime_demo(self,tid,uid):
time.sleep(tid)
threading_id=threading.current_thread().ident
big_list[uid]=threading_id
@tornado.gen.coroutine#异步、协程处理;增加并发量
defpost(self):
globalall_count
all_count+=1
uid=str(uuid4())
yieldself.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()#结束服务
defget(self):
returnself.post()
__init__.py
'''
@File:__init__.py
@Copyright:rainbol
@Date:2020/8/31
@Desc:
'''
importtornado.web#web框架
importtornado.httpserver#http服务
importtornado.ioloop#输入输出事件循环
importtornado.options#配置工具
fromtornado.optionsimportoptions,define
fromapp.configimportconfigs
fromapp.urlsimporturls
define('port',default=8000,type=int,help='运行端口')
#自定义应用
classCustomApplication(tornado.web.Application):
def__init__(self):#重写构造方法
#指定路由规则
handlers=urls
#指定配置文件
settings=configs
super(CustomApplication,self).__init__(handlers=handlers,**settings)
#定义服务
defcreate_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: ''' fromapp.viewsimportcreate_server if__name__=='__main__': create_server()
路由
fromapp.views.views_indeximportIndexHandlerasindex fromapp.views.views_serviceimportServiceHandlerasservice #配置路由和配置到映射规则 urls=[ (r"/index",index), (r"/demo",service), ]
以上就是pythonTornado框架的使用示例的详细内容,更多关于pythonTornado框架的资料请关注毛票票其它相关文章!