【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()
相关推荐
大布布将军20 小时前
⚡️ 深入数据之海:SQL 基础与 ORM 的应用
前端·数据库·经验分享·sql·程序人生·面试·改行学it
JIngJaneIL20 小时前
基于java+ vue农产投入线上管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
源代码•宸21 小时前
goframe框架签到系统项目(BITFIELD 命令详解、Redis Key 设计、goframe 框架教程、安装MySQL)
开发语言·数据库·经验分享·redis·后端·mysql·golang
川贝枇杷膏cbppg21 小时前
Redis 的 AOF
java·数据库·redis
TG:@yunlaoda360 云老大21 小时前
如何在华为云国际站代理商控制台进行SFS Turbo的性能与容量核查?
服务器·网络·数据库·华为云
ytttr87321 小时前
MATLAB基于LDA的人脸识别算法实现(ORL数据库)
数据库·算法·matlab
云老大TG:@yunlaoda3601 天前
如何进行华为云国际站代理商跨Region适配?
大数据·数据库·华为云·负载均衡
思成不止于此1 天前
【MySQL 零基础入门】事务精讲(二):ACID 特性与并发问题
数据库·笔记·学习·mysql
Boilermaker19921 天前
[MySQL] 初识 MySQL 与 SQL 基础
数据库·mysql
今晚务必早点睡1 天前
Redis——快速入门第二课:Redis 常用命令 + 能解决实际问题
数据库·redis·bootstrap