Tornado 异步服务器和客户端模块client

一、Tornado 异步服务器和客户端模块client

@tornado.gen.coroutine与yield tornado.gen.sleep(3)构建异步服务

time.sleep(5) # 同步实现

async_server.py

 import tornado.ioloop
    import tornado.web
    import os
    import time
    import datetime as dt
    
    class SleepHandler(tornado.web.RequestHandler):
        @tornado.gen.coroutine # 做协程 与yield tornado 实现异步
        def get(self):
            # time.sleep(5)  # 同步实现
            yield tornado.gen.sleep(3)
            self.write(str(dt.datetime.now()))
    
    def make_app():
        return tornado.web.Application(
            [
            (r"/sleep", SleepHandler),  # r"" 后面是路径
            ],
            debug=True
        )
    
    if __name__ == "__main__":
        app = make_app()
        app.listen(8888)
        tornado.ioloop.IOLoop.current().start()

async_client.py

"""
Created on 19-2-19

@author: 260207

@requirement:Anaconda 4.3.0 (64-bit) Python3.6 

@description:
"""
import requests
import time

import tornado.gen
import tornado.httpclient
import tornado.ioloop
from tornado import gen

N = 3
URL = 'http://localhost:8888/sleep'

# 异步方式请求 以N=3为例:async 3.0119595527648926
@gen.coroutine
def main():
    http_client = tornado.httpclient.AsyncHTTPClient()
    response = yield [
        http_client.fetch(URL) for i in range(N)
    ]

beg1 = time.time()
tornado.ioloop.IOLoop.current().run_sync(main)
print('async', time.time() - beg1)


# 同步方式请求 时间翻倍req 9.040810823440552
beg = time.time()
for i in range(N):
    requests.get(URL)
print('req', time.time()-beg)

**

建立两个.py文件进行异步与同步测试,同步方式请求时间较长,三秒请求三次,时间九秒多,异步时间三秒多,相互干扰小,速度快。

**
Tornado 异步服务器和客户端模块client_第1张图片
随笔:今天是元宵节,附上一张走心的图片,祝福团圆、快乐。

你可能感兴趣的:(tornado)