久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

python Tornado框架的使用示例

瀏覽:4日期:2022-07-07 18:33:05

Tornado是一個python的開源web框架,它比django要輕量級到多,也沒有什么組件,只有運用到對應到業務場景下我才使用這個框架,它是單進程單線程到異步非阻塞模型,適用與長連接長輪巡,高并發,異步非阻塞

安裝:

pip install tornado

View層

’’’@File : views_service.py@Copyright : rainbol@Date : 2020/8/31@Desc :’’’import threadingimport timeimport tornado.webimport tornadoimport tornado.ioloopimport tornado.webimport tornado.genfrom tornado.concurrent import run_on_executorfrom concurrent.futures import ThreadPoolExecutorfrom uuid import uuid4import randomall_count = 0big_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, definefrom app.config import configsfrom app.urls import urlsdefine(’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_serverif __name__ == ’__main__’: create_server()

路由

from app.views.views_index import IndexHandler as indexfrom app.views.views_service import ServiceHandler as service# 配置路由和配置到映射規則urls = [ (r'/index', index), (r'/demo', service),]

以上就是python Tornado框架的使用示例的詳細內容,更多關于python Tornado框架的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 元谋县| 盱眙县| 酉阳| 伊宁市| 普洱| 定兴县| 阿图什市| 山东| 秀山| 莱阳市| 建瓯市| 日喀则市| 阿拉尔市| 康定县| 永丰县| 黄陵县| 集贤县| 景泰县| 舟山市| 永平县| 乌兰察布市| 玉田县| 浦江县| 南康市| 苍梧县| 石渠县| 贞丰县| 温泉县| 泾源县| 张家口市| 盐池县| 沾益县| 绵竹市| 玉田县| 蓬安县| 萝北县| 江油市| 正蓝旗| 四会市| 敦化市| 西贡区|