【python3】tornado高性能编程

  • 使用多进程充分利用cpu
  • 使用异步编程 asyncio
python 复制代码
import asyncio
import time
from abc import ABC
from concurrent.futures import ProcessPoolExecutor
from tornado import web, ioloop, gen


async def async_task(name):
    print(f"start: {name}")
    st = int(time.time())
    time.sleep(3)  # 模拟同步等待 
    await asyncio.sleep(3)  # 模拟异步等待
    result = f"task: {name}, start: {st}, end: {int(time.time())}"
    return result


def run_async_task(name):
    return asyncio.run(async_task(name))


class MainHandler(web.RequestHandler, ABC):
    executor = ProcessPoolExecutor()  # 进程池

    @gen.coroutine
    def get(self):
        task_name = self.get_argument("task", "task-1")
        result = yield self.executor.submit(run_async_task, task_name)
        self.write(result)


def make_app():
    return web.Application([
        (r"/", MainHandler),
    ])


if __name__ == '__main__':
    app = make_app()
    app.listen(8888)
    print("http://localhost:8888/?task=task-X")
    ioloop.IOLoop.current().start()
相关推荐
缓慢更新16 小时前
AI 辅助生成单测:从接口定义到用例的流水线
java·服务器·前端·网络·数据库·人工智能
AI小百科16 小时前
向量数据库:AI 的「记忆仓库」是怎么工作的
数据库·人工智能·oracle
煎饼皮皮侠16 小时前
【设计】设计一个Web版数据库管理平台(之七):多数据库类型易扩展
数据库
Nturmoils16 小时前
MongoDB迁移之后,Spring Data 和 Hibernate 各自接哪类请求
数据库
画中有画16 小时前
在自动化脚本中操作本地数据库
数据库·oracle·自动化
Decay__16 小时前
09_MySQL 闪回与时间点恢复 —— binlog 回放、mysqlbinlog、PITR 与误删恢复
运维·数据库·sql·mysql·架构
太理摆烂哥17 小时前
MySQL用户管理
数据库·mysql
梦影_19 小时前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database
考虑考虑19 小时前
mariadb数据库
数据库·后端·mariadb
John_Hui20 小时前
Windows 10 安装版本:mysql-8.1.0-winx64.zip
数据库·windows·mysql